Skip to content

Instantly share code, notes, and snippets.

@1xch
Last active December 14, 2015 23:39
Show Gist options
  • Save 1xch/5166807 to your computer and use it in GitHub Desktop.
Save 1xch/5166807 to your computer and use it in GitHub Desktop.
Manage jinja2 macros with code
from flask import get_template_attribute
from jinja2 import Template
class MacroFor(object):
""" Use this as a mixin
e.g.
class ListItemBasic(MacroFor):
def __init__(self, listitem):
self.title = listitem.title
self.description = listitem.description
super(ListItemBasic, self).__init__(macro_var = "list_item_basic_macro", # macro name with the macro file
macro = "macros/list-item-basic.html") # location of the macro
then if you have any datastructure full of these, iterate and call
{% for item in listitems %}
{{ item.render }}
{% endfor %}
"""
def __init__(self, macro_var, macro):
self.macro_var = macro_var
self.macro = macro
@property
def render(self):
return get_template_attribute(self.macro, self.macro_var)(self)
class InternalMacro(object):
"""
Manipulates or creates a macro given a name, macro text, and type of content to fill(is_tuple, is_dict, is_list, is_file).
Set content_is to 'passthrough' and kwarg 'to_pass' to move "something else" through this (useful where you
need to mix "something else" with internal macros for this a use case of this class, e.g. internally collating varied
aggregations of macros dependent on varied states or permissions
"""
def __init__(self, name = None,
text = None,
content_is = None,
**kwargs):
self.macro_name = "{}_template".format(name)
self.macro_var = "{}_macro".format(name)
self.text = text
self.content_is = content_is
self.macro = self.format_macro
if content_is is 'passthrough':
self.passthough = kwargs['to_pass'] or None
@property
def is_static(self):
return "{{% macro {0}() %}}{1}{{% endmacro %}}".format(self.macro_var, self.text)
@property
def is_tuple(self):
return "{{% macro {0}(t) %}}{1}{{% endmacro %}}".format(self.macro_var, self.text)
@property
def is_dict(self):
return "{{% macro {0}(items) %}}{{% for k,v in items.iteritems() %}}{1}{{% endfor %}}{{% endmacro %}}".format(self.macro_var, self.text)
@property
def is_list(self):
return "{{% macro {0}(items) %}}{{% for i in items %}}{1}{{% endfor %}}{{% endmacro %}}".format(self.macro_var, self.text)
@property
def is_file(self):
return self.text
@property
def format_macro(self):
t = getattr(self, self.content_is)
if self.content_is is 'is_file':
return t
else:
return self.return_template(t)
def return_template(self, t):
return Template(t)
@property
def return_callable(self):
if hasattr(self, 'passthrough'):
return self.passthrough
else:
return get_template_attribute(self.macro, self.macro_var)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment