在 if 比较字符串中呈现模板对象

Rendering template object in an if comparison string

我一直在尝试这样做,但没有结果

<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/”,但这似乎不起作用。

我认为您不能在 {% %} 中使用 {{ }},因此您需要以不同的方式执行此操作。有很多可能性。

尝试使用

 {% if request.get_full_path == "/topic/"+topic.topic_slug+"/" %}

但我的方法是简单地使用您的 class 来完成 return 路径的工作。 /topic/tech/ 看起来像人们通常 return 从 get_absolute_url class 函数:

 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())。