开发者

How to use template variable in a template tag in Django?

开发者 https://www.devze.com 2023-01-27 18:49 出处:网络
I have a custom template tag called cg {% cg %} and I hava a varialbe {{ s开发者_运维知识库tatus }}

I have a custom template tag called cg

{% cg %}

and I hava a varialbe {{ s开发者_运维知识库tatus }}

I need to wrap the result of {{ status }} inside a <special></special> HTML tag, and then pass into {%cg %}, how to write this code in django template?


You can write your own filter like this:

from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter
@stringfilter
def wrap(value, tag):
    return mark_safe("<%(tag)s>%(value)s</%(tag)s>" % {'value': value, 'tag': tag})

and use it in template: {% cg status|wrap:"special" %}

Edit-fixed.


"Passing template variables to the tag"

0

精彩评论

暂无评论...
验证码 换一张
取 消