Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments to django's custom template (block) tags

I was trying to make reusable interface components with django. I was able to pull something off with custom template tags:

{% panel %}
    Some panel content
{% endpanel %}

It works fine but I wasn't able to pass the panel title as an argument. What I really wanted was something like:

{% panel 'Panel Title' %}
    Some panel content
{% endpanel %}

I couldn't find an answer for this in the docs. Is there a way to achieve it? If not, is there another strategy that I could use?

edit: Keep in mind that the panel content is suposed to accept more markup inside, like other tags and blocks. That's why a simple template tag was not enough for me.


Details

panel.html

<div class="panel panel-default">
    <div class="panel-heading">{{ title|default:"Panel Title" }}</div>
    <div class="panel-body">
        {{ body }}
    </div>
</div>

templatetags/theme.py

from django import template


register = template.Library()


@register.tag
def panel(parser, token):
    nodelist = parser.parse(('endpanel',))
    parser.delete_first_token()
    return PanelNode(nodelist)


class PanelNode(template.Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist

    def render(self, context):
        output = self.nodelist.render(context)
        t = template.loader.get_template('theme/blocks/panel.html')
        c = template.Context({'body': output})
        return t.render(c)
like image 418
Hugo Mota Avatar asked Oct 20 '22 07:10

Hugo Mota


1 Answers

I believe the answer you are looking for is written in the documentation, https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#passing-template-variables-to-the-tag

Go down to the section of simple tags and it details how to pass vairable the way you want to

@register.simple_tag
def my_tag(a, b, *args, **kwargs):
    warning = kwargs['warning']
    profile = kwargs['profile']
    ...
    return ...

Then in the template any number of arguments, separated by spaces, may be passed to the template tag. Like in Python, the values for keyword arguments are set using the equal sign (“=”) and must be provided after the positional arguments. For example:

{% my_tag 123 "abcd" book.title warning=message|lower profile=user.profile %}
like image 168
harshadbhatia Avatar answered Nov 01 '22 12:11

harshadbhatia