Skip to content

Instantly share code, notes, and snippets.

@loicteixeira
Last active September 15, 2016 20:26
Show Gist options
  • Save loicteixeira/68054c7297c395c47820 to your computer and use it in GitHub Desktop.
Save loicteixeira/68054c7297c395c47820 to your computer and use it in GitHub Desktop.
[Django] Options block in Template

Add the possibility to save options to the current context.

Save the different files in the proper folders:

DJANGO_PROJECT
  APP_NAME
    templates
      APP_NAME
        index.html
    templatetags
      options.py
    views.py
{% load options %}
{% options btn_opt %}
{
"class": [
"btn",
"btn-primary",
"btn-options"
],
"text": "{{ button_text }}",
"type": "button"
}
{% endoptions %}
<button type="{{ btn_opt.type }}" class="{{ btn_opt.class|join:' ' }}">{{ btn_opt.text }}</button>
from django import template
import json
register = template.Library()
class OptionNode(template.Node):
def __init__(self, option_name, nodelist):
self.option_name = option_name
self.nodelist = nodelist
def render(self, context):
node_content = self.nodelist.render(context)
context[self.option_name] = json.loads(node_content)
return ''
@register.tag
def options(parser, token):
option_name = token.split_contents()[-1]
nodelist = parser.parse(('endoptions',))
parser.delete_first_token()
return OptionNode(option_name, nodelist)
from django.shortcuts import render
def index(request):
context = {
'button_text': "List all"
}
return render(request, 'APP_NAME/index.html', context=context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment