将命名URL的值分配给Django模板中的变量 [英] Assign Value of Named URL to a Variable in Django Templates

查看:46
本文介绍了将命名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 %}

这篇关于将命名URL的值分配给Django模板中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆