sebastien.worms
sebastien.worms

Reputation: 344

Django: test url regex in template

I have a same template that is used for different urls (in this case: /create/ and /edit/[PK of an item] , named "create" and "edit" in the url.py).

I would like to show different things in my template depending if I'm on /edit/ or /create/.

How can I check this ? {% if '/create' in request.path %} works, but I'd like to use a url tag (or equivalent, to not have it "hard coded"). What I would like to do looks like (in pseudo code - this doesn't work) {% if request.path in url create %} XXX {% endif %}.

Should I make all the necessary tests in the views.py, send a variable about it in the context, test on this variable in the template? In my case it seems a bit heavy for a simple url test ...

Upvotes: 2

Views: 2976

Answers (3)

JamesO
JamesO

Reputation: 25946

You can set a url with a as value.

{% url 'some-url-name' arg arg2 as the_url %}

{% if the_url in request.path %}

Upvotes: 3

Intenex
Intenex

Reputation: 1947

I'd say go for making two views if it's a significant difference (different form, etc.) - eliminates url logic in templates entirely, and no real 'test' needed either - don't have to check request.path/pass url/etc.

urls

urlpatterns = patterns('',
    (r'^create/$', create),
    (r'^edit$', edit),
)

views

def create(request):
    text = "Create something"
    return render_to_response('same-template.html', {'text': text}, context_instance=RequestContext(request)

def edit(request):
    text = "Edit something"
    return render_to_response('same-template.html', {'text': text}, context_instance=RequestContext(request)

template

{% text %}

Can also pass multiple changes easily with a list this way too:

views

def create(request):
    data = []
    data['text'] = "Create something"
    data['form'] = CreateForm()
    return render_to_response('same-template.html', {'data': data}, context_instance=RequestContext(request)

def edit(request):
    data = []
    data['text'] = "Edit something"
    data['form'] = EditForm()
    return render_to_response('same-template.html', {'data': data}, context_instance=RequestContext(request)

template

{% data.text %}
{% data.form %}

Upvotes: 2

Jure C.
Jure C.

Reputation: 3080

Either you do it in a view, or write a template tag.

Looking on django snippets, this one looks nice: http://djangosnippets.org/snippets/1531/

Upvotes: 0

Related Questions