【问题标题】:Rendering template object in an if comparison string在 if 比较字符串中呈现模板对象
【发布时间】:2018-02-01 21:44:41
【问题描述】:
我一直在尝试这样做,但没有得到任何结果
<ul>
{% for topic in topics %}
<li {% if request.get_full_path == "/topic/{{ topic.topic_slug }}/" %}class="is-active"{% endif %}>
<a href="{% url "TopicView" topic.topic_slug %}">{{ topic.topic_name }}</a>
</li>
{% endfor %}
</ul>
我猜这个错误来自于字符串中呈现的 {{ topic.topic_slug }}。我希望在渲染期间它是“/topic/tech/”,但这似乎不起作用。
【问题讨论】:
标签:
django
django-templates
django-template-filters
【解决方案1】:
我不相信您可以在{% %} 中使用{{ }},因此您需要以不同的方式执行此操作。有很多可能性。
尝试使用
{% if request.get_full_path == "/topic/"+topic.topic_slug+"/" %}
但我这样做的方式是简单地使用您的类来完成返回路径的工作。 /topic/tech/ 看起来像人们通常从 get_absolute_url 类函数返回的内容:
class Topic:
...
def get_absolute_url(self):
return '/topic/{}/'.format(self.topic_slug)
然后在您的模板中,只需使用:
{% if request.get_full_path == topic.get_absolute_url %}
(请注意,如果您已经有一个 absolute_url,只需使用另一个函数名称。例如 get_my_topic_slug_url())。