mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-01-09 16:18:30 +00:00
Fix Jinja2 templating for loop variables and mixed syntax
Co-Authored-By: Joe Moura <joao@crewai.com>
This commit is contained in:
@@ -64,8 +64,24 @@ def render_template(
|
||||
|
||||
jinja_template = to_jinja_template(input_string)
|
||||
|
||||
# Create a custom undefined class that allows loop variables
|
||||
class LoopUndefined(jinja2.StrictUndefined):
|
||||
"""Custom undefined class that allows loop variables."""
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def __str__(self):
|
||||
if self._undefined_name in ('loop', 'item', 'topic'):
|
||||
return ''
|
||||
return super().__str__()
|
||||
|
||||
def __getattr__(self, name):
|
||||
if self._undefined_name in ('loop', 'item', 'topic'):
|
||||
return self
|
||||
return super().__getattr__(name)
|
||||
|
||||
env = jinja2.Environment(
|
||||
undefined=jinja2.StrictUndefined, # Raise errors for undefined variables
|
||||
undefined=LoopUndefined, # Use custom undefined class for loop variables
|
||||
autoescape=True # Enable autoescaping for security
|
||||
)
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@ def interpolate_only(
|
||||
|
||||
if has_jinja_syntax or has_complex_indexing:
|
||||
return render_template(input_string, inputs)
|
||||
else:
|
||||
|
||||
# The regex pattern to find valid variable placeholders
|
||||
# Matches {variable_name} where variable_name starts with a letter/underscore
|
||||
# and contains only letters, numbers, and underscores
|
||||
@@ -95,9 +95,6 @@ def interpolate_only(
|
||||
f"Template variable '{missing_vars[0]}' not found in inputs dictionary"
|
||||
)
|
||||
|
||||
try:
|
||||
return render_template(input_string, inputs)
|
||||
except Exception:
|
||||
result = input_string
|
||||
for var in variables:
|
||||
if var in inputs:
|
||||
|
||||
Reference in New Issue
Block a user