【问题标题】:Django custom tag: Inclusion tag with no contextDjango 自定义标签:没有上下文的包含标签
【发布时间】:2011-11-29 14:00:51
【问题描述】:

我已经阅读了custom tags and filters documentation,但我不知道如何做到这一点。我想制作一个只呈现字符串的自定义标签。没有上下文,每次都是相同的字符串文字。在这种特殊情况下,我更喜欢这样而不是把 {% include 'hello_world.htm' %} 到处都是:

Foo, foo foo
<br>
{% hello_world %}
<br>
bar bar bar

呈现给:

Foo, foo foo
<br>
"Hello World"
<br>
bar bar bar

我觉得我应该能够通过以下方式做到这一点:

custom_tags.py:

from django import template
register = template.Library()

@register.inclusion_tag('hello_world.htm')
def hello_world():
     return {}

# Or:

def hello_world():
     return {}
register.inclusion_tag('hello_world.htm', takes_context=False)(hello_world)

没有骰子。我在 custom_tags.py 中有其他自定义标签,我正在加载它们,它们工作正常,但总是得到 ​​p>

Invalid block tag: 'hello_world', expected 'endblock' or 'endblock content'

文档说

标签比过滤器更复杂,因为标签可以做任何事情。

...你如何用标签做最简单的事情?

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    你可以用一个简单的标签来做到这一点:https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#shortcut-for-simple-tags

    from django import template
    
    register = template.Library()
    
    @register.simple_tag
    def hello_world():
        return u'Hello world'
    

    然后在你的模板中你可以写{% hello_world %}来渲染字符串。

    【讨论】:

    • 不,他是,使用包含标签,因为他也在渲染模板。
    • 是的,这就是他正在做的事情,但问题是“我想制作一个只呈现字符串的自定义标签”,这就是我的解决方案所提供的。
    猜你喜欢
    • 2011-01-23
    • 2012-12-22
    • 2012-01-14
    • 2011-08-10
    • 2011-04-21
    • 2017-03-26
    • 2010-10-30
    • 2012-06-06
    • 2012-08-20
    相关资源
    最近更新 更多