13

I'm trying to simply get the current Site from within a template for parsing like so:

<h3>{{ site.name }}</h3>

Unfortunately, this isn't bringing anything up.

Is there a way to get access to the current site from a template?

Naftuli Kay
  • 87,710
  • 93
  • 269
  • 411

2 Answers2

27

The title of your question presumes that "view" and "template" are interchangeable -- they're not. In order to get the current site in a template, it needs to be added to the context that is used to render the template. If you're using a RequestContext, you can write a context processor to do this automatically.

You can write a context processor to do this like so:

from django.contrib.sites.models import Site

def site_processor(request):
    return { 'site': Site.objects.get_current() }

Then, add it to your TEMPLATE_CONTEXT_PROCESSORS, and use it like so:

<h3>{{ site.name }}</h3>
Naftuli Kay
  • 87,710
  • 93
  • 269
  • 411
bradley.ayers
  • 37,165
  • 14
  • 93
  • 99
  • I'm using `django.views.generic.simple.direct_to_template`, so I should be covered, right? There isn't a built-in context processor for this? – Naftuli Kay Sep 19 '11 at 05:17
  • Yes, `direct_to_template` uses `RequestContext`, however you'll need to write your own context processor as there isn't one in Django. Alternatively you can pass an argument to `direct_to_template` that adds the current site to the context. – bradley.ayers Sep 19 '11 at 05:23
  • Why is the function named `site_processor` instead of `site`? – Chris Johnson Apr 24 '14 at 21:10
  • @ChrisJohnson: The function is a [context processor](https://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors), and that's what the function name implies. It returns a `dict`, and the keys in the dict will be made available as variables when rendering the context. Thus you could change the `site` key to something else, or add additional key/value pairs to the dictionary and access them as well in the template. – Simon Apr 30 '14 at 09:51
  • Still the best answer to provide this to a template, but it is worth noting the setting location changed in 1.8: https://docs.djangoproject.com/en/1.9/ref/templates/upgrading/#the-templates-settings – Jmills Mar 24 '16 at 17:54
  • Awesome! Thank you. Consider editing your answer to illustrate how to add a context_procesor to code base and to `settings.py` file. – MadPhysicist Jun 20 '17 at 16:26
0

Weirdly, using the bradleyayers processor gave Null results, so instead of using the Site framework, I used the parameter inside the request.

So the processor will look like that :

def host_processor(request):
    return { 'host': request.get_host() }

Hope it helped

Juanwolf
  • 840
  • 9
  • 19