开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜