Skip to content

Commit

Permalink
template context update
Browse files Browse the repository at this point in the history
  • Loading branch information
Alzpeta committed Dec 6, 2023
1 parent 6687122 commit bdc68e8
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 9 deletions.
97 changes: 94 additions & 3 deletions oarepo_ui/resources/catalog.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import os
import re
from itertools import chain
from pathlib import Path

import flask
import jinja2
from flask import current_app
from flask.globals import request
from jinjax import Catalog
from jinjax.component import Component
from jinjax.exceptions import ComponentNotFound
from jinjax.jinjax import JinjaX

DEFAULT_URL_ROOT = "/static/components/"
ALLOWED_EXTENSIONS = (".css", ".js")
Expand All @@ -20,9 +25,95 @@
class OarepoCatalog(Catalog):
singleton_check = None

def __init__(self):
super().__init__()
self.jinja_env.undefined = jinja2.Undefined
def __init__(
self,
*,
globals: "dict[str, t.Any] | None" = None,
filters: "dict[str, t.Any] | None" = None,
tests: "dict[str, t.Any] | None" = None,
extensions: "list | None" = None,
jinja_env: "jinja2.Environment | None" = None,
root_url: str = DEFAULT_URL_ROOT,
file_ext: "TFileExt" = DEFAULT_EXTENSION,
use_cache: bool = True,
auto_reload: bool = True,
) -> None:
self.prefixes: "dict[str, jinja2.FileSystemLoader]" = {}
self.collected_css: "list[str]" = []
self.collected_js: "list[str]" = []
self.file_ext = file_ext
self.use_cache = use_cache
self.auto_reload = auto_reload

root_url = root_url.strip().rstrip(SLASH)
self.root_url = f"{root_url}{SLASH}"

# env = jinja2.Environment(undefined=jinja2.StrictUndefined)
env = flask.templating.Environment(undefined=jinja2.Undefined, app=current_app)
extensions = [*(extensions or []), "jinja2.ext.do", JinjaX]
globals = globals or {}
filters = filters or {}
tests = tests or {}

if jinja_env:
env.extensions.update(jinja_env.extensions)
globals.update(jinja_env.globals)
filters.update(jinja_env.filters)
tests.update(jinja_env.tests)
jinja_env.globals["catalog"] = self
jinja_env.filters["catalog"] = self

globals["catalog"] = self
filters["catalog"] = self

for ext in extensions:
env.add_extension(ext)
env.globals.update(globals)
env.filters.update(filters)
env.tests.update(tests)
env.extend(catalog=self)

self.jinja_env = env

self._cache: "dict[str, dict]" = {}

def update_template_context(self, context: dict) -> None:
"""Update the template context with some commonly used variables.
This injects request, session, config and g into the template
context as well as everything template context processors want
to inject. Note that the as of Flask 0.6, the original values
in the context will not be overridden if a context processor
decides to return a value with the same key.
:param context: the context as a dictionary that is updated in place
to add extra variables.
"""
names: t.Iterable[t.Optional[str]] = (None,)

# A template may be rendered outside a request context.
if request:
names = chain(names, reversed(request.blueprints))

# The values passed to render_template take precedence. Keep a
# copy to re-apply after all context functions.

for name in names:
if name in self.jinja_env.app.template_context_processors:
for func in self.jinja_env.app.template_context_processors[name]:
context.update(func())

def render(
self,
__name: str,
*,
caller: "t.Callable | None" = None,
**kw,
) -> str:
self.collected_css = []
self.collected_js = []
if "context" in kw:
self.update_template_context(kw["context"])
return self.irender(__name, caller=caller, **kw)

def get_source(self, cname: str, file_ext: "TFileExt" = "") -> str:
prefix, name = self._split_name(cname)
Expand Down
8 changes: 4 additions & 4 deletions oarepo_ui/resources/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,6 @@ def detail(self):
)

metadata = dict(serialized_record.get("metadata", serialized_record))
_catalog.jinja_env.globals["current_user"] = current_user


return _catalog.render(
"detail",
Expand All @@ -185,6 +183,7 @@ def detail(self):
record=serialized_record,
extra_context=extra_context,
ui_links=ui_links,
context=_catalog.jinja_env.globals,
)

def _get_record(self, resource_requestctx, allow_draft=False):
Expand Down Expand Up @@ -276,6 +275,7 @@ def search(self):
layout=layout,
ui_links=ui_links,
extra_context=extra_context,
context=_catalog.jinja_env.globals,
)

@request_read_args
Expand Down Expand Up @@ -365,7 +365,6 @@ def edit(self):

_catalog.jinja_env.globals["current_user"] = current_user


return _catalog.render(
"edit",
__source=source,
Expand All @@ -374,6 +373,7 @@ def edit(self):
extra_context=extra_context,
ui_links=ui_links,
data=data,
context=_catalog.jinja_env.globals,
)

@login_required
Expand Down Expand Up @@ -422,7 +422,6 @@ def create(self):

_catalog.jinja_env.globals["current_user"] = current_user


return _catalog.render(
"create",
__source=source,
Expand All @@ -431,6 +430,7 @@ def create(self):
extra_context=extra_context,
ui_links={},
data=empty_record,
context=_catalog.jinja_env.globals,
)

@property
Expand Down
1 change: 0 additions & 1 deletion oarepo_ui/theme/webpack.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
"oarepo_ui_forms": "./js/oarepo_ui/forms/index.js",
"oarepo_ui_theme": "./js/oarepo_ui/theme.js",
"oarepo_ui_components": "./js/custom-components.js",

},
dependencies={
"@tanstack/react-query": "^4.32.0",
Expand Down
2 changes: 1 addition & 1 deletion tests/test_ui_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


def test_ui_resource_create_new(app, record_ui_resource, record_service):
assert record_ui_resource.empty_record(None) == {"title": ''}
assert record_ui_resource.empty_record(None) == {"title": ""}


def test_ui_resource_form_config(app, record_ui_resource):
Expand Down

0 comments on commit bdc68e8

Please sign in to comment.