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

Pass Arguments to jinja Template #756

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
47 changes: 46 additions & 1 deletion eel/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,8 @@ def _static(path: str) -> btl.Response:
if path.startswith(template_prefix):
n = len(template_prefix)
template = _start_args['jinja_env'].get_template(path[n:])
response = btl.HTTPResponse(template.render())
# Pass the context variables to the template
response = btl.HTTPResponse(template.render(**_context.get_all()))

if response is None:
response = btl.static_file(path, root=root_path)
Expand Down Expand Up @@ -646,3 +647,47 @@ def _set_response_headers(response: btl.Response) -> None:
if _start_args['disable_cache']:
# https://stackoverflow.com/a/24748094/280852
response.set_header('Cache-Control', 'no-store')


class Context:
'''Class to manage variables that will be passed to Jinja templates.

This class provides a way to store and retrieve variables that will be made
available to Jinja templates when they are rendered.
'''

def __init__(self) -> None:
self._variables: Dict[str, Any] = {}

def set(self, name: str, value: Any) -> None:
'''Set a variable that will be available in Jinja templates.

:param name: Name of the variable to be used in templates.
:param value: Value to associate with the variable name.
'''
self._variables[name] = value

def get(self, name: str) -> Any:
'''Get a variable value by name.

:param name: Name of the variable to retrieve.
:returns: The value associated with the variable name.
'''
return self._variables.get(name)

def get_all(self) -> Dict[str, Any]:
'''Get all variables as a dictionary.

:returns: Dictionary of all variable names and values.
'''
return self._variables.copy()

# Add after the existing global variables
_context: Context = Context()

def get_context() -> Context:
'''Get the global Context instance for setting template variables.

:returns: The global Context instance.
'''
return _context
4 changes: 4 additions & 0 deletions examples/06 - jinja_templates/hello.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

eel.init('web') # Give folder containing web files

context = eel.get_context()
context.set('users', ['Alice', 'Bob', 'Charlie'])
context.set('title', 'Hello from Eel!')

@eel.expose
def py_random():
return random.random()
Expand Down
13 changes: 10 additions & 3 deletions examples/06 - jinja_templates/web/templates/hello.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,14 @@
eel.say_hello_py("Javascript World!"); // Call a Python function
{% endblock %}
{% block content %}
Hello, World!
<br />
<h1>{{ title }}</h1>

<h2>Users:</h2>
<ul>
{% for user in users %}
<li>{{ user }}</li>
{% endfor %}
</ul>

<a href="page2.html">Page 2</a>
{% endblock %}
{% endblock %}
15 changes: 14 additions & 1 deletion tests/integration/test_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,21 @@ def test_06_jinja_templates(driver: webdriver.Remote):
driver.get(eel_url)
assert driver.title == "Hello, World!"

h1_element = driver.find_element(By.CSS_SELECTOR, 'h1')
assert h1_element.text == "Hello from Eel!"

user_elements = driver.find_elements(By.CSS_SELECTOR, 'ul li')
expected_users = ['Alice', 'Bob', 'Charlie']

assert len(user_elements) == len(expected_users), "Number of rendered users doesn't match expected"

for user_elem, expected_user in zip(user_elements, expected_users):
assert user_elem.text == expected_user, f"Expected user {expected_user}, got {user_elem.text}"

driver.find_element(By.CSS_SELECTOR, 'a').click()
WebDriverWait(driver, 2.0).until(expected_conditions.presence_of_element_located((By.XPATH, '//h1[text()="This is page 2"]')))
WebDriverWait(driver, 2.0).until(
expected_conditions.presence_of_element_located((By.XPATH, '//h1[text()="This is page 2"]'))
)


def test_10_custom_app(driver: webdriver.Remote):
Expand Down