开发者

Django custom tag: Inclusion tag with no context

开发者 https://www.devze.com 2023-04-10 18:15 出处:网络
I\'ve read through the custom tags and filters documentation, but I\'m not seeing how this can be done. I want to make a custom tag that just renders a string. No context, just the same string literal

I've read through the custom tags and filters documentation, but I'm not seeing how this can be done. I want to make a custom tag that just renders a string. No context, just the same string literal every time. In this particular case, I would prefer this over putting {% include 'hello_world.htm' %} all over the place:

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

Renders to:

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

I feel like I should be able to do this with something like:

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)

No dice. I have other custom tags in custom_tags.py, I am l开发者_运维问答oading them and they work fine, but always getting

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

The documentation says

Tags are more complex than filters, because tags can do anything.

... how do you do the simplest thing possible with tags?


You can do this with a simple tag: 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'

then in your template you can write {% hello_world %} to render the string.

0

精彩评论

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