Let me start by saying that I am fully aware that I can capture template 
content with macro feature. However, macro requires writing macro and 
invoking a macro, while with capture I can simply write content and declare 
a variable the content should be stored in. So, the goal is to send the 
content to the variable that is going to be used in a macro invocation.

I started with code listed on StackOverflow, but I it did not work. Below 
you will find the solution that I created. I don't know Jinja2 internals, 
so I have no idea if this solution may have any side effects or if there is 
an easier way to accomplish my goal.

Could you review it and give me a feedback?

Thanks

P.S. I am coming from PHP Smarty that has a capture tag, which simplified 
my life a few times.

from jinja2 import nodesimport jinja2from jinja2.ext import Extension
class CaptureExtension(Extension):
    """
    Generic HTML capture, inspired by Rails' capture helper

    In any template, you can capture an area of content and store it in a global
    variable:

    {% capture 'name_of_variable' %}
        blah blah blah 
    {% endcapture %}
    {% capture 'a'  %}panorama{% endcapture %}

    To display the result
    {{ captured['name_of_variable'] }}
    {{ captured['a'] }}

    The context is global, and works within macros as well, so it's useful for 
letting macros define
    javascript or <head> tag content that needs to go at a particular position
    on the base template.

    Inspired by 
http://stackoverflow.com/questions/4292630/insert-javascript-at-top-of-including-file-in-jinja-2
    and http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html
    """
    tags = set(['capture'])

    def __init__(self, environment):
        super(CaptureExtension, self).__init__(environment)
        assert isinstance(environment, jinja2.Environment)
        self._myScope = {}
        environment.globals['captured'] = self._myScope

    def parse(self, parser):
        """Parse tokens """
        assert isinstance(parser, jinja2.parser.Parser)
        tag = parser.stream.next()
        args = [parser.parse_expression()]
        body = parser.parse_statements(['name:endcapture'], drop_needle=True)
        return nodes.CallBlock(self.call_method('_capture', args),[], [], 
body).set_lineno(tag.lineno)

    def _capture(self, name, caller):
        self._myScope[name] = caller()
        return ""


-- 
You received this message because you are subscribed to the Google Groups 
"pocoo-libs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/pocoo-libs?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to