Dave Martorana
Dave Martorana

Reputation: 1331

Jinja2 extensions - get the value of variable passed to extension

So I have a Jinja2 extension. Basically follows the parser logic, except that I need to get a value from the parsed args being passed in.

For instance, if I have an extension called loadfile, and pass it a variable:

{% loadfile "file.txt" %}

when I grab the argument through parser.parse_expression() I get a node.Const variable that has a .value argument - and I can get the name file.txt no problem.

However...

{% set filename = "file.txt" %}
{% loadfile filename %}

causes me issues. The parser gives me a node.Name expr node, which neither responds to .value or the as_const(...) call that all other nodes respond to.

I can't figure out how to evaluate the value of the node.Name node I'm getting from parsing the arguments, and thus cannot get the name file.txt.

Is there a good way to parse argument variables/values in an extension so that I can use them to execute the extention?

Thanks!

Upvotes: 2

Views: 1235

Answers (1)

erthalion
erthalion

Reputation: 3244

This works for me

def parse(self, parser):
    lineno = parser.stream.next().lineno

    # args will contains filename
    args = [parser.parse_expression()]

    return nodes.Output([
        nodes.MarkSafeIfAutoescape(self.call_method('handle', args))
    ]).set_lineno(lineno)

def handle(self, filename):
    # bla-bla-bla

Upvotes: 1

Related Questions