Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Specify loader for jinja template (external Jinja template support) #138

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/dynamicprompts/generators/jinjagenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,11 @@ def _build_jinja_template(self, template: str):
PromptExtension,
)

env = jinja2.Environment(extensions=[PromptExtension])
env_kwargs = dict(extensions=[PromptExtension])
# If wildcard root is specified, set it as jinja template root, also
if self._wildcard_manager.path:
env_kwargs.update(loader=jinja2.FileSystemLoader(self._wildcard_manager.path))
env = jinja2.Environment(**env_kwargs)
prompt_blocks: list[str] = []
env.globals.update(
{
Expand Down
20 changes: 20 additions & 0 deletions tests/generators/test_jinja.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,23 @@ def test_ignore_whitespace(self, generator: JinjaGenerator):
prompts = generator.generate(template)
for p in prompts:
assert "\n" not in p

def test_jinja_template_from_file(self, generator: JinjaGenerator):
template = """
{%- import 'jinja/lib.jinja' as lib -%}
{{ lib.echo('test') -}}
"""
assert generator.generate(template) == ["test"]

with patch("random.choice") as mock_choice:
mock_choice.side_effect = ["red", "blue", "red"]
template = """
{%- import 'jinja/lib.jinja' as lib with context -%}
{{ lib.mychoice() -}}
"""

assert generator.generate(template, 3) == [
"This is a red rose",
"This is a blue rose",
"This is a red rose",
]
6 changes: 6 additions & 0 deletions tests/test_data/wildcards/jinja/lib.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{% macro echo(arg) -%}
{{ arg }}
{%- endmacro %}
{% macro mychoice() -%}
This is a {{ choice('red', 'blue') }} rose
{%- endmacro %}