将命名URL的值分配给Django模板中的变量
在我的Django模板中,我需要将名称url的值分配给with块中的变量,以便可以在多个地方使用它。
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 %}
但显然不起作用,最终会导致解析错误。上面的示例是一个简单的场景,其中我可以只使用{%url showtag tag%}而不是{{tagabs}}并删除with块。但是在我的场景中,tagabs值需要在多个地方和if语句中使用它进行比较。
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.
感谢您的帮助。
如果功能位于核心位置,为什么还要创建新的模板标签/过滤器?
Why create a new template tag/filter if the feature is in core?
样本位于: 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>
和
{% url 'path.to.view' as the_url %}
{% if the_url %}
<a href="{{ the_url }}">Link to optional stuff</a>
{% endif %}