To build an HTML string from a Jinja2 template file in Python, you will need to have Jinja2 installed in your environment. If it's not installed, you can install it using pip:
pip install Jinja2
Here's a Python function that reads a Jinja2 template file, renders it with the provided context (variables), and returns the resulting HTML string:
from jinja2 import Environment, FileSystemLoader, select_autoescape
def render_html_from_template(template_path, template_name, context):
"""
Renders an HTML string from a Jinja2 template file.
:param template_path: The file system path to the directory containing Jinja2 templates.
:param template_name: The name of the Jinja2 template file to be rendered.
:param context: A dictionary containing the context variables for the template.
:return: The rendered HTML string.
"""
# Create a Jinja2 environment with the path to the templates
env = Environment(
loader=FileSystemLoader(template_path),
autoescape=select_autoescape(['html', 'xml'])
)
# Load the template by name
template = env.get_template(template_name)
# Render the template with the provided context
html = template.render(context)
return html
# Example usage:
if __name__ == "__main__":
# Define the path to the directory where your templates are stored
templates_path = 'path/to/your/templates'
# Define the template file name
template_file_name = 'your_template.html'
# Define the context (variables) to pass to the template
context_variables = {
'title': 'My Page Title',
'body_content': 'This is the body content of the page.'
}
# Render the HTML string
rendered_html = render_html_from_template(templates_path, template_file_name, context_variables)
# Print the rendered HTML
print(rendered_html)
Make sure that you have the following directory structure:
/path/to/your/templates/
└── your_template.html
And in your your_template.html Jinja2 template file, you might have something like this:
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<p>{{ body_content }}</p>
</body>
</html>
This render_html_from_template function will take the your_template.html file, render it with the provided context_variables, and return the resulting HTML as a string.