templatetag to call an urlconf and store its payload into the template context
pip install django-rest-caller==0.2.2
Simple django templatetag for calling an urlconf view endpoint.
Install with pip
$ python3 -m pip install django-rest-caller
Add caller.apps.CallerConfig
to INSTALLED_APPS
INSTALLED_APPS = [
...
'caller.apps.CallerConfig',
...
]
In your template load the templatetag
{% load caller_tags %}
and use the call
tag as
{% call 'urlconf' arg1=42 arg2='X' with param1='1' param2='2' as 'object_name' %}
or
{% call 'urlconf' 42 'X' with param1='1' param2='2' as 'object_name' %}
'urlconf' arg1=42 arg2='X'
this is the usual {% url %} parameters (remember: use args parameter list or kwargs parameters, not both)param1='1' param2='2'
these parameters will be converted to GET querystringas 'object_name'
store the called object into object_name object. It can be a string or a variable name.so the called url is equivalent to
{% url 'urlconf' arg1=42 arg2='X' %}?param1=1¶m2=2
The call
will inject the result json object into the template context, so you can
{% load caller_tags %}
{% call 'api:blog-list' as 'posts' %}
{% for post in posts %}
<div>
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
{% endfor %}
{% load caller_tags %}
{% call 'api:blog-list' as 'posts' %}
{{ posts|json_script:"posts-data" }}
<script>
function get_json(node) {
var el = document.getElementById(node);
return JSON.parse(el.textContent || el.innerText);
}
var posts = get_json("posts-data");
console.log(posts);
</script>
This tag will backport the django >= 2.1 json_script
filter,
which safely outputs a Python object as JSON, wrapped in a <script>
tag, ready for use with JavaScript.
with
value = {'hello': 'world'}
and
{{ value|json_script:"hello-data" }}
will output
<script id="hello-data" type="application/json">{"hello": "world"}</script>
and can be retrieved with
function get_json(name) {
var el = document.getElementById(name);
return JSON.parse(el.textContent || el.innerText);
}
var data = get_json("hello-data");
console.log(data);
as 'varname'