How to load jinja template directly from filesystem

前端 未结 4 721
挽巷
挽巷 2020-12-12 23:43

The jinja API document at pocoo.org states:

The simplest way to configure Jinja2 to load templates for your application looks roughly like this:
相关标签:
4条回答
  • 2020-12-12 23:44

    Here is the one liner:

    template = Template(open('template_file.j2').read())
    

    Then you can render the template on another line, or for all in one line:

    rendered = Template(open('template_file.j2').read()).render(var="TEXT")
    
    0 讨论(0)
  • 2020-12-12 23:45

    A simpler way is to directly call the jinj2.Template constructor and use open to load the file:

    from jinja2 import Template
    with open('template.html.jinja2') as file_:
        template = Template(file_.read())
    template.render(name='John')
    
    0 讨论(0)
  • 2020-12-12 23:57

    Here's how: use a FileSystemLoader instead of a PackageLoader. I found examples on the web here and here. Let's say you have a python file in the same dir as your template:

    ./index.py
    ./template.html
    

    This index.py will find the template and render it:

    #!/usr/bin/python
    import jinja2
    
    templateLoader = jinja2.FileSystemLoader(searchpath="./")
    templateEnv = jinja2.Environment(loader=templateLoader)
    TEMPLATE_FILE = "template.html"
    template = templateEnv.get_template(TEMPLATE_FILE)
    outputText = template.render()  # this is where to put args to the template renderer
    
    print(outputText)
    

    It turns out, the jinja2 API doc does have a section which discusses all the built-in loaders, so it's kind of embarrassing not to have noticed that right away. But the introduction is worded such that PackageLoader seems to be the default, "simplest" method. For newcomers to python, this can lead to a wild goose chase.

    0 讨论(0)
  • 2020-12-13 00:09

    If using Python 3.4+ and Jinja2 - v2.11+ -- we can combine python's pathlib and Filesystem to simplify the flow

    from pathlib import Path
    ...
    
    p = Path(__file__).parent.parent / 'templates' # sample relative path
    env = Environment(
        loader=FileSystemLoader(Path(p)))
    template = env.get_template('your_file.jinja2')
    

    I am not comfortable with using directly Template(file) since Jinja's template inheritance processing may not work well.

    Pathlib support is only added in latest version of Jinja - v2.11+

    0 讨论(0)
提交回复
热议问题