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) |