2017-07-31 82 views
0

我有神社問題Jinja2的YAML蟒蛇哈希問題

generate.py:

from jinja2 import Template 
import yaml 
import sys 
import os.path 

#Parse the YAML file and produce a Python dict. 
yaml_vars = yaml.load(open('parameters.yaml').read()) 

#Load the Jinja2 template into a Python data structure. 
template = Template(open('skel.j2').read()) 

#Render the configuration using the Jinja2 render method using yaml_vars as arg. 
rendered_config = template.render(yaml_vars) 

#Write the rendered configuration to a text file. 
with open('config.txt', 'w') as config: 
    config.write(rendered_config) 

parameters.yaml

city : LA 

skel.j2沒有任何問題

123qwe 

skel.j2出現問題

{{ 

錯誤:

Traceback (most recent call last): 
    File "generate.py", line 10, in <module> 
    template = Template(open('skel.j2').read()) 
    File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 945, in __new__ 
    return env.from_string(source, template_class=cls) 
    File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 880, in from_string 
    return cls.from_code(self, self.compile(source), globals, None) 
    File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 591, in compile 
    self.handle_exception(exc_info, source_hint=source_hint) 
    File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 780, in handle_exception 
    reraise(exc_type, exc_value, tb) 
    File "<unknown>", line 2, in template 
jinja2.exceptions.TemplateSyntaxError: unexpected end of template, expected 'end of print statement'. 

問:我如何可以禁用字符串處理 '{{'?

回答

3

正如the documentation建議,在你的輸出獲得{{最簡單的方法是實際打印:

{{ '{{' }} 

,或者,你可以使用一個raw塊:

{% raw %} 
    {{ 
{% endraw %}