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.
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 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.
{% 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 .
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With