Reputation: 77
Situation: I'm using Django 1.9. And i have a javascript loop that takes some javascript stored in database. This js has some django tags that i want to load when that js is loaded into my template. This is the function:
{% extends "base_clean.html" %}
{% load i18n %}
{% block title %}{% trans "Campaign" %} - {{ campaign.name }}{% endblock %}
{% block content %}
Some HTML
Some CSS
<script type="text/javascript">
Some javascript functions.
displayed = 0;
delay = 1000;
(function loop() {
setTimeout(function() {
p = pq.getMessage()
if( p != false ) {
posthtml = get_message_html(p);
displayed++;
{{ display_style.layout.js|safe }} /* !!!!!!!!!!!!!!!!!!*/
if( pq.messagesCount() < 10 ){
pq.getMessages()
}
loop();
}, delay);
})();
</script>
{% endblock %}
And this is what {{ display_style.layout.js|safe }} load:
setTimeout(function() {
$('#messages_container').append(posthtml);
{% if display_style.post_append_effect %}
$(posthtml).addClass("animated {{ display_style.post_append_effect.css }}");
{% endif %}
}, 900);
}
if(displayed == {{ display_style.messages_per_page }}){
delay = {{ display_style.seconds_between_messages }}000;
}
if(displayed > {{ display_style.messages_per_page }}){
$target = $('#messages_container div.list-group-item').first()
{% if display_style.message_remove_effect %}
$target.removeClass("animated {{ display_style.post_append_effect.css }}")
.addClass("animated {{ display_style.post_remove_effect.css }}");
{% endif %}
setTimeout(function() {
$target.remove();
displayed--
}, 900);
}
As you can see it has some django tags that i also want to render. But i've got "Uncaught SyntaxError: Unexpected token %"
EDIT: Added django header tags. and structure of the templates And forgot to say that if i write explicitly the js that i want to render to my template it works... problem is trying to render tags into the rendered js
Upvotes: 2
Views: 4099
Reputation: 28732
I think the issue is that you're loading a second template as a text string rather than using Django's include
template tag. Try changing {{ display_style.layout.js|safe }}
to {% include "display_style.layout.js" %}
and any syntax error should become more apparent.
You should also consider using Django's staticfiles to load your javascript rather than including javascript in your template. Then per this answer you can simply define the variables you want to pass to your javascript in a <script>
tag that you can reference in your javascript file. Something like:
{% load staticfiles %}
<!-- Some html -->
<script>
var displayStyle = {{ display_style }};
</script>
<script type="text/javascript" src="{% static 'your_js_file.js' %}"></script>
<!-- Rest of your HTML -->
var displayStyle = window.displayStyle || null;
if (displayStyle) {
// Your code here.
}
Last, one possibility for the specific error is that your included template has a %
character somewhere. This would need to be escaped as %%
in the django templating system.
Upvotes: 2