Obtain the first part of an URL from Django template

孤街浪徒 提交于 2019-12-03 10:45:28

You can not pass arguments to normal python functions from within a django template. To solve you problem you will need a custom template tag: http://djangosnippets.org/snippets/806/

You can use the slice filter to get the first part of the url

{% if request.path|slice:":5" == '/test' %}
    Test
{% endif %} 

Cannot try this now, and don't know if filters work inside 'if' tag, if doesn't work you can use the 'with' tag

{% with request.path|slice:":5" as path %}
  {% if path == '/test' %}
    Test
  {% endif %} 
{% endwith %} 

Instead of checking for the prefix with startswith, you can get the same thing by checking for membership with the builtin in tag.

{% if '/test' in request.path %}
    Test
{% endif %} 

This will pass cases where the string is not strictly in the beginning, but you can simply avoid those types of URLs.

You can't, by design, call functions with arguments from Django templates.

One easy approach is to put the state you need in your request context, like this:

def index(request):
    c = {'is_test' : request.path.startswith('/test')}
    return render_to_response('index.html', c, context_instance=RequestContext(request))

Then you will have an is_test variable you can use in your template:

{% if is_test %}
    Test
{% endif %}

This approach also has the advantage of abstracting the exact path test ('/test') out of your template, which may be helpful.

From the Philosophy section in this page of Django docs:

the template system will not execute arbitrary Python expressions

You really should write a custom tag or pass a variable to inform the template if the path starts with '/test'

I use context processor in such case:

*. Create file core/context_processors.py with:

def variables(request):
        url_parts = request.path.split('/')
        return {
            'url_part_1': url_parts[1],
        }

*. Add record:

'core.context_processors.variables',

in settings.py to TEMPLATES 'context_processors' list.

*. Use

{{ url_part_1 }}

in any template.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!