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.
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)
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With