5

I have jinja template file with variable names like x.y.z (like java package names). Then I'm using Python envtpl to generate actual config file from jinja template file using envtpl.process_file. But it errors out saying 'x' is undefined. I know in jinja dot means something else so how do I escape it so that envtpl understands that 'x.y.z' is a variable name not just 'x'.

template file for example:

foo = "{{ x.y.z | default("abc") }}"
bar = "{{ a.b.c | default("123") }}"
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
Himanshu Shah
  • 51
  • 1
  • 3
  • A Jinja template needs a context to be rendered with. How do you define it? – Klaus D. Feb 09 '16 at 00:36
  • I am not using Jinja directly so not sure how do I define that. I'm using this Python library : https://github.com/andreasjansson/envtpl for generating a file from a template. – Himanshu Shah Feb 09 '16 at 00:44
  • So your context is your environment. A dot is not allowed in environmental variable names. Can you give a example of your environment? – Klaus D. Feb 09 '16 at 00:59
  • Create a global function like this {% get_var(x, y, z) %} More here: http://stackoverflow.com/questions/6036082/call-a-python-function-from-jinja2 – voscausa Feb 09 '16 at 02:53
  • Thanks all for replying. I couldn't find good solution, so now I convert dot in my variables name to underscore before passing them to envtpl. – Himanshu Shah Feb 22 '16 at 18:33

2 Answers2

1

If someone is still interested in this, this worked for me:

/* model */
...
some_function('some.value')
...



{# macro #}
{% macro some_function(value) %}
    {% set data = {{ "'"+value+"'" }} %}
    {{ data }}
{% endmacro %} 

OR

{# macro #}
{% macro some_function(value) %}
    {% set data = {{ "'%s'" % value }} %}
    {{ data }}
{% endmacro %}
0

Escaping it with single quotes worked for me inside of conditionals. For example:

{% if 'x.y.z' is defined -%}
Jorge V.
  • 172
  • 6