Is the current Site accessible from a template?
Asked Answered
E

2

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?

Emanative answered 19/9, 2011 at 5:9 Comment(0)
M
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>
Marlin answered 19/9, 2011 at 5:13 Comment(6)
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?Emanative
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.Marlin
Why is the function named site_processor instead of site?Deflective
@ChrisJohnson: The function is a context processor, 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.Milburt
Still the best answer to provide this to a template, but it is worth noting the setting location changed in 1.8: docs.djangoproject.com/en/1.9/ref/templates/upgrading/…Colubrine
Awesome! Thank you. Consider editing your answer to illustrate how to add a context_procesor to code base and to settings.py file.Flamen
G
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

Girondist answered 21/3, 2015 at 22:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.