Include S3 files by jinja2

Asked 2 years ago, Updated 2 years ago, 41 views

Thank you for your help.

I'd like to include the file on S3 with the include feature of python3 HTML template jinja2, but I don't know what to do.

<divid="sample">
    <!--Read sample HTML-->
    {% include "https://.../sample.html"%}
</div>

As mentioned above, specifying the full path of the HTML file on S3 also failed.

Ideally, I would like to download HTML on S3 into memory and embed the data in the div tag with jinja2. What should I do?

python html python3

2022-09-29 22:56

1 Answers

You cannot include a file on your network using the include feature of jinja2, but you can do it by writing a function to retrieve it and passing it to jinja2 at render.

Below is a sample code.

 from jinja2 import Environment, select_autoescape, FileSystemLoader
import urllib.request

def include_from_url(url):
    with urllib.request.urlopen(url)asf:
        return f.read()

env=Environment(
    loader=FileSystemLoader('.',
    autoescape=select_autoescape(['html','xml'],
)
template=env.get_template('template.html')
print(template.render(include_from_url=include_from_url))

template.html

<divid="sample">
    <!--Read sample HTML-->
    {{include_from_url('https://.../sample.html')}}
</div>

If you are using flask, you can use Context Processors.
Documentation http://flask.pocoo.org/docs/1.0/templating/ #context-processors

@app.context_processor
utility_processor():
    def include_from_url(url):
        with urllib.request.urlopen(url)asf:
            return f.read()


2022-09-29 22:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.