Custom tags

Django templates offer a versatile set of built-in tags. It is quite easy to create your own custom tag. Since custom tags live inside an app, create a templatetags directory inside an app. This directory must be a package, so it should have an (empty) __init__.py file.

Next, write your custom template in an appropriately named Python file. For example, for this active link pattern, we can create a file called nav.py with the following contents:

# app/templatetags/nav.py 
from django.core.urlresolvers import resolve 
from django.template import Library 
 
register = Library() 
@register.simple_tag 
def active_nav(request, url): 
    url_name = resolve(request.path).url_name 
    if url_name == url: 
        return "active" 
    return "" 

This file defines a custom tag named active_nav. It retrieves the URL's path component from the request argument (say, /about/). Then, the resolve() function is used to look up the URL pattern's name (as defined in urls.py) from the path. Finally, it returns the string "active" only when the pattern's name matches the expected pattern name.

The syntax for calling this custom tag in a template is {% active_nav request 'pattern_name' %}. Notice that the request needs to be passed in every page that this tag is used.

Including a variable in several views can get cumbersome. Instead, we add a built-in context processor to TEMPLATE_CONTEXT_PROCESSORS in settings.py so that the request will be present in a request variable across the site, as follows:

# settings.py 
    [          
        'django.core.context_processors.request', 
    ] 

Now, all that remains is to use this custom tag in your template to set the active attribute:

{# base.html #} 
{% load nav %} 
<ul class="nav nav-pills"> 
  <li class={% active_nav request 'active1' %}><a href="{% url 'active1' %}">Active 1</a></li> 
  <li class={% active_nav request 'active2' %}><a href="{% url 'active2' %}">Active 2</a></li> 
  <li class={% active_nav request 'active3' %}><a href="{% url 'active3' %}">Active 3</a></li> 
</ul> 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset