You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have a macro somewhere in code, and I want to be able to render that macro by itself. But it contains {{ csrf_input }} call (app is written in Django obviously), and I don't understand how to pass it to a macro. So I had to resort to an ugly hack of using from_string. Here is my code:
from django import http
from django.template import loader, engines, backends
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
def render_macro(request, template_name, macro_name, **ctx):
jinja = next(e for e in engines.all()
if isinstance(e, backends.jinja2.Jinja2))
t = jinja.env.from_string(
'{%% from "%s" import card with context %%}{{ %s(**ctx) }}'
% (template_name, macro_name))
reqctx = {
"ctx": ctx,
"request": request,
"csrf_input": csrf_input_lazy(request),
"csrf_token": csrf_token_lazy(request),
}
for context_processor in jinja.template_context_processors:
reqctx.update(context_processor(request))
markup = t.render(reqctx)
return http.HttpResponse(markup)
# this one won't render context argh
def render_macro_better(request, template_name, macro_name, **ctx):
tmpl = loader.get_template(template_name)
mod = tmpl.template.module
macro = getattr(mod, macro_name)
reqctx = {
"request": request,
"csrf_input": csrf_input_lazy(request),
"csrf_token": csrf_token_lazy(request),
}
for context_processor in tmpl.backend.template_context_processors:
reqctx.update(context_processor(request))
markup = macro(**ctx)
return http.HttpResponse(markup)
I wonder if there is a way to pass reqctx to a macro in the second case?
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I have a macro somewhere in code, and I want to be able to render that macro by itself. But it contains
{{ csrf_input }}
call (app is written in Django obviously), and I don't understand how to pass it to a macro. So I had to resort to an ugly hack of usingfrom_string
. Here is my code:I wonder if there is a way to pass
reqctx
to a macro in the second case?Beta Was this translation helpful? Give feedback.
All reactions