Anuj TBE
Anuj TBE

Reputation: 9826

could not use custom templatetags in Django 2.0

I'm using Django 2.0.

I have written few custom template tags to use in the template inside notes/templatetags/note_tags.py file where notes is app directory

I have written few custom tags inside this file

from django import template
from django.template.defaultfilters import stringfilter
from notepad.utils import simplify_text
from notes.models import Note, ColorLabels

register = template.Library()


@register.filter(name='note_simplify')
@stringfilter
def note_simplify(value):
    return simplify_text(value)


@register.filter(name='default_color_label')
def default_color_label():
    default_label = ColorLabels.objects.filter(default=True).first()
    print(default_label.value)
    return default_label

and inside the template file, I have loaded the tag as

{% load note_tags %}

I'm able to use the first tag note_simplify but second tag default_color_label is not being called. I'm using both tags in the same file. One for modifying the passed data and another to simply print something

# modify the note.content
<p>{{ note.content|truncatechars:200|note_simplify }}</p>

# to print some value
{{ default_color_label.value }}

I have also restared server many times.

Is there something wrong? Why the tag is not being called in template?

Upvotes: 1

Views: 1500

Answers (1)

Satendra
Satendra

Reputation: 6865

You need simple_tag here, if you want an object in template.

@register.simple_tag  
def default_color_label():
    default_label = ColorLabels.objects.filter(default=True).first()
    return default_label

And in HTML you can use it.

{% default_color_label as variable %}
{{ variable.value }}

Note: You have defined filter not tag and also you are using it incorrectly. template filters are always used with pipe operator. {{ somevalue|default_color_label }}

UPDATE

assignment_tag Deprecated since version 1.9 simple_tag can now store results in a template variable and should be used instead.

Upvotes: 3

Related Questions