Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign Value of Named URL to a Variable in Django Templates

Tags:

django

In my Django template I need to assign the value of a names url into a variable within a with block so I can use it in multiple places.

I need to achieve something like this:

{% for tag in post.tags.all %}
    {% with tagabs={%url showtag tag%} %}
          <li><a href="{{tagabs}}">#{{tag}}</a></li>
    {% endwith %}
{% endfor %}

But obviously that doesn't work and would end up with a parsing error. The above example is a simple scenario where I could just have {%url showtag tag%} instead of {{tagabs}} and remove the with block. But in my scenario the tagabs value I need to use it in several places and within an if statement for comparison.

Thanks for the help.

like image 474
Ayman Farhat Avatar asked Apr 25 '13 16:04

Ayman Farhat


People also ask

How do I declare a variable inside a Django template?

Another approach to declare variables in the template is by using custom template tags. Create a custom template tag files named as custom_template_tags.py . Paste the below code in it. Now inside the HTML template use this custom template tag setvar to define a new variable.

What {{ NAME }} means in a Django template?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

What does form {% url %} do?

{% url 'contact-form' %} is a way to add a link to another one of your pages in the template. url tells the template to look in the URLs.py file. The thing in the quotes to the right, in this case contact-form , tells the template to look for something with name=contact-form .


Video Answer


1 Answers

Why create a new template tag/filter if the feature is in core?

Look the samples at: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#url

{% url 'path.to.view' arg arg2 as the_url %}

<a href="{{ the_url }}">I'm linking to {{ the_url }}</a>

and

{% url 'path.to.view' as the_url %}
{% if the_url %}
  <a href="{{ the_url }}">Link to optional stuff</a>
{% endif %}
like image 152
Darwin Avatar answered Oct 10 '22 12:10

Darwin