简体   繁体   中英

How can I use a Sekizai javascript block in a Django template filter?

I am writing a Django template filter. I would it like to insert some javascript. In brief: is there a way to add to the Sekizai "js" block in this filter, but have it render in the "js" block defined on the page template?

To make my question clearer, the following filter does what I want, but without Sekizai: (leaving out auto-escaping for simplicity)

from django import template
from django.template import Context
register = template.Library()
@register.filter  
def myfilter(text):
    context = { "text": text }
    myhtml = get_template('mytemplate.html')
    return myhtml.render(Context(context))

where mytemplate.html has some javascript in it, eg:

<canvas id="xyz" width="200" height="200"></canvas>
<script>
function drawCircle(context, radius, centerX, centerY, color) {
    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI);
    context.fillStyle = color;
    context.fill();
}
var canvas = document.getElementById('xyz');
var context = canvas.getContext('2d');
drawCircle(context,50,100,100,"blue");
</script>

This works fine.

However, with Sekizai, I want the <script>...</script> in mytemplate.html to be added to the "js" block:

{% addtoblock "js" %}<script>...</script>{% endaddtoblock %}

(Using Sekizai also requires a change to the filter:

from sekizai.context import SekizaiContext
...
    return myhtml.render(SekizaiContext(context))

)

But this doesn't work, because the template filter does not have a "js" block - so the javascript is never rendered. However, there is a "js" block in the bigger picture, eg the filter is being called from a template that looks like this:

{% load sekizai_tags %}
<head>...</head>
<body>
     {{ info|myfilter }}
     {% render_block "js" %}
</body>

So... is there a way around this problem? Can I add to a Sekizai block in my template filter, and have it render on the page template?

Thanks!

Django template filters don't inherit the global template context, but inclusion tags can (if you set takes_context=True in the inclusion_tag decorator).

I'd suggest you refactor your code to use an inclusion tag instead of a filter, in which case sekizai blocks might work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM