Search code examples
djangodjango-templatesdjango-template-filters

Rendering template object in an if comparison string


I've been trying to do this and getting no results

<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>

The error, I'm guessing is from the {{ topic.topic_slug }} being rendered in the string. I'd like it to be "/topic/tech/" during rendering but that seems not to be working.


Solution

  • I don't believe you can use {{ }} inside a {% %} so you need to do this in a different way. There are many possibilities.

    Try using

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

    but the way I would do it is to simply use your class to do the work of returning the path. /topic/tech/ looks like what people usually return from a get_absolute_url class function:

     class Topic:
    
         ...
    
         def get_absolute_url(self):
             return '/topic/{}/'.format(self.topic_slug)
    

    and then in your template, simply use:

     {% if request.get_full_path == topic.get_absolute_url %}
    

    (Note that if you already have an absolute_url, simply use another function name. e.g. get_my_topic_slug_url()).