pjbeardsley
pjbeardsley

Reputation: 1531

Using string literals as parameters to template tags in Django templates

One of the things I find myself doing often is passing string literals as parameters to template tags or functions; for instance:

{% url my-url 'my_param' %}

Unfortunately, the django template engine doesn't let you do this. So I find myself doing this a lot in my view code:

my_context_dict['MY_PARAM'] = 'my_param'

and then in my view code:

{% url my-url MY_PARAM %}

Or creating a series of URL mappings, which I personally try to avoid.

Is it possible to use a string literal in Django templates? Or possibly a more elegant solution? I haven't seen anything on here or in the documentation.

Upvotes: 10

Views: 9687

Answers (3)

Rick
Rick

Reputation: 11

Very wierd - I have a django project that uses single quotes to pass a string value and it functions just fine.

<a href="{% url categories 'vendor' %}"</a>
<a href="{% url categories 'crew' %}"</a>

On further investigation it turns out this has changed in django 1.5. It now requires the quotes even around the url pattern name.

Upvotes: 1

S.Lott
S.Lott

Reputation: 391846

This feels wrong but is right.

<a href="{% url someting "param1" "param2" %}">text</a>

The nested ""'s don't seem like they should work. They do. The Django {% %} material is simply pulled out of the HTML without regard for surrounding context. So the "duplicated" "'s aren't really duplicated at all.

Upvotes: 14

Ayman Hourieh
Ayman Hourieh

Reputation: 137156

Use double quotes instead of single quotes:

{% url my_view "my_param" %}

Upvotes: 12

Related Questions