Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NamedTuples in Jinja2 template macros

The saga continues, extended from the original thread.

So, I have a something to make macros within python code:

from flask import get_template_attribute
from jinja2 import Template

    class InternalMacro(object):
        """
        Creates a macro given a name, internal macro text, and content to fill(as namedtuple(t.var), dict(k,v), list(i), or other)
        """
        def __init__(self, name = None,
                           text = None,
                           content_is = None):
            self.name = name
            self.macro_name = "{}_template".format(self.name)
            self.macro_var = "{}_macro".format(self.name)
            self.text = text
            self.content_is = content_is
            self.macro_txt = self.format_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 format_text(self):
            return getattr(self, self.content_is)

        @property
        def return_template(self):
            return Template(self.macro_txt)

        @property
        def return_callable(self):
            return get_template_attribute(self.return_template, self.macro_var)

Which I pass namedtuples singly, as lists, or as dicts. This works when passing a list (haven't fully tested as dict, yet) but does not work when passing a single namedtuple. No matter what, so far, the namedtuple gets escaped as unicode.

So given:

test_macro = InternalMacro('test', '{{ t }} <div id="divvy">{{ t.var }}</div>', 'is_tuple')

test_macro.return_callable(Anamedtuple)

returns:

u'Anamedtuple(var="A VAR VALUE") <div id="divvy"></div>'

not:

u'Anamedtuple(var="A VAR VALUE")' <div id="divvy">A VAR VALUE</div>

If I do this as list, .var get called normally.

What is going on that I'm missing and how do I circumvent this? The single namedtuple gets escaped, but a list does not. I could do the single one as a list and just pop the first, maybe seems unclean to me. Any suggestions on improving this appreciated as well.

EDIT:

Simple solution was to just reduce everything to a passed in list, eliminate single and dict options, just pass in a list of 1. Still I'd like to figure out what is going on there exactly.

EDIT2:

A deeper explore showed that the way I output the namedtuple generated the results I was seeing ie -

test_macro = InternalMacro('test', '{{ t }} <div id="divvy">{{ t.var }}</div>', 'is_tuple')

results in:

u'Anamedtuple(var="A VAR VALUE") <div id="divvy"></div>'

whereas:

test_macro = InternalMacro('test', '<div id="divvy">{{ t.var }}</div>', 'is_tuple')

results in

'<div id="divvy">A VAR VALUE</div>'

I guess the namedtuples get read once or....well any detailed explanation appreciated.

like image 291
blueblank Avatar asked Dec 30 '12 16:12

blueblank


1 Answers

Possibly not what you want but...

from collections import namedtuple

x = namedtuple("Foo", "var")
z = x(var = 123)
with app.app_context():
    test_macro = InternalMacro('test', "'{{ t }}' <div id=\"divvy\">{{ t.var }}</div>", 'is_tuple')
    returnVal = test_macro.return_callable(z)

print returnVal
#'Foo(var=123)' &lt;div id="divvy"&gt;123&lt;/div&gt;

'Foo(var=123)' <div id="divvy">123</div>

repr(returnVal)
'u\'\\\'Foo(var=123)\\\' <div id="divvy">123</div>\''

I'm using Python 2.7 with Flask 0.10.1 ( it's been a while ).

The tip off was the expectation of something that is not explicitly defined. Unless I missed it there's no discrimination between how basic types ( int, str, etc ) and class objects anywhere in the InternalMarco's is_tuple() property. Also for an is_tuple, everything is put together in one string and that's printed to buffer.

The behavior is different from for i in items which flushes each for loop body {i} ( assuming it was a typo putting a {1}) and doesn't do any string appends.

env/Python27/lib/site-packages/jinja2/parser.py is where I believe this happens

Line #869

elif token.type == 'block_begin':
  flush_data()
  next(self.stream)
  if end_tokens is not None and \
                   self.stream.current.test_any(*end_tokens):
     return body
  rv = self.parse_statement()
  if isinstance(rv, list):
     body.extend(rv)
  else:
     body.append(rv)
  self.stream.expect('block_end')
like image 64
David Avatar answered Sep 20 '22 13:09

David