0

With the following renderer...

from django.shortcuts import render
...
return render(request, 'template.html', {'context':context,})

Is it possible to override the render classe's methods so that I can in certain circumstances interpret template tags myself for example if I find a tag consisting of a certain format such as...

{% url 'website' page.slug %}

I could point it to...

/theme/theme-1/page.html

or

/theme/theme-2/page.html

depending on extranious settings.

Stephen Brown
  • 564
  • 1
  • 9
  • 23

1 Answers1

1

The render method is just a shortcut for:

template = loader.get_template(''template.html')
context = {
    ...,
}
return HttpResponse(template.render(context, request))

Therefore, it is not the correct place to try to change the behaviour of the url tag.

For the example you have given, it looks like the website should be a variable that holds theme-1 or theme-2. You can then pass the variable to the url tag instead of the string 'website'.

{% url website page.slug %}

If that is not possible, you could create a custom template tag my_url that returns the correct url depending on your settings.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Someone else will be responsible for the creation of the templates and will instincitly use {% url %} I just want to be able to load multiple websites in one program and intercept the routing when nessesary. This will be a library of themes but the code must run normally once added to an actual site. – Stephen Brown Jul 07 '17 at 13:53
  • as @alasdair pointed out, Instead of changing default behavior of render you should try custom template tags. Have a look at this SO post for an example https://stackoverflow.com/questions/6451304/django-simple-custom-template-tag-example – cutteeth Jul 07 '17 at 13:54
  • You could replace Django's url tag with your own tag using the [`BUILTINS`](https://docs.djangoproject.com/en/1.11/topics/templates/#module-django.template.backends.django) option. I don't think that's a good idea though. You could also look at [`TemplateResponse`](https://docs.djangoproject.com/en/1.11/ref/template-response/#templateresponse-objects) instead of `render`, since it has extra hooks. – Alasdair Jul 07 '17 at 14:12