Home > Enterprise >  How to Use Custom Template Tag in Combination With Django's Built-in "with" Tag?
How to Use Custom Template Tag in Combination With Django's Built-in "with" Tag?

Time:10-19

I have this simple tag:

myapp/templatetags/my_filters.py

@register.simple_tag
def get_bookmark_object(content_type, object_id):
    return Bookmark.objects.get(content_type=content_type, object_id=object_id)

In my template, I want to be able to do this:

{% load my_filters %}

{% with object as bookmark %}
  {% with bookmark_object=get_bookmark_object bookmark.content_type bookmark.object_id %}
    {% if bookmark.content_type.model == 'post' %}
      {% include 'content/post/object.html' with object=bookmark_object user_bookmark=bookmark %}
    {% elif bookmark.content_type.model == 'note' %}
      {% include 'content/note/object.html' with object=bookmark_object user_bookmark=bookmark %}
    {% endif %}
  {% endwith %}
{% endwith %}

I get the error:

TemplateSyntaxError at /my-page/
'with' received an invalid token: 'bookmark.content_type'

My question is:

How do I use my custom get_bookmark_object template tag in a with statement? An example with code would help me clarify a lot.

Reference: Django's with built-in

CodePudding user response:

What you defined is a template tag, you can assign the value produced by the template tag with an {% … as … %} tag:

{% get_bookmark_object bookmark.content_type bookmark.object_id as bookmark_object %}
    …
  • Related