Skip to content

Commit

Permalink
chore: jinja
Browse files Browse the repository at this point in the history
  • Loading branch information
timurbazhirov committed Jan 18, 2025
1 parent 901e266 commit 1f5b71c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
26 changes: 21 additions & 5 deletions src/py/mat3ra/utils/extra/jinja.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,33 @@
from jinja2 import Environment, FileSystemLoader


def render_template_file(template_file: str, **kwargs):
def render_template_file(template_file_path: str, **kwargs):
"""
Renders a given template file.
Args:
template_file (str): template file path
template_file_path (str): template file path
kwargs: variables passed to the template
Returns:
str
"""
env = Environment(loader=FileSystemLoader(os.path.dirname(template_file)))
template_file = env.get_template(os.path.basename(template_file))
return template_file.render(**kwargs)
env = Environment(loader=FileSystemLoader(os.path.dirname(template_file_path)))
template_file_path = env.get_template(os.path.basename(template_file_path))
return template_file_path.render(**kwargs)


def render_template_string(template_string: str, **kwargs):
"""
Renders a given template string.
Args:
template_string (str): template string
kwargs: variables passed to the template
Returns:
str
"""
env = Environment()
template = env.from_string(template_string)
return template.render(**kwargs)
9 changes: 6 additions & 3 deletions tests/py/unit/test_extra_jinja.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@

FILE_JINJA_TEMPLATE_PATH = Path(__file__).parent / "./fixtures/file_jinja_template.jinja"


def test_render_template():
"""
test_camel_to_snake should be converted to testCamelToSnake
"""
context = {"name": "World"}
rendered = utils.render_template_file(FILE_JINJA_TEMPLATE_PATH, **context)
assert rendered == "Hello, World!"

def test_render_template_string():
context = {"name": "World"}
rendered = utils.render_template_string("Hello, {{ name }}!", **context)
assert rendered == "Hello, World!"

0 comments on commit 1f5b71c

Please sign in to comment.