Stuart Grimshaw
Stuart Grimshaw

Reputation: 1571

Can I override blocks in the parent template from Django templatetags?

I'm writing a templatetag package for Django to make including RGraph graphs in Django apps easy.

I'm having a bit of trouble with the template that includes the javascript, I have a block defined in my base html file that I would like the templatetag's template to provide.

This is my top level template

{% load django_rgraph %}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title>Test Charts</title>
    {% block js %}
    {% block js.custom %}{% endblock %}
    {% endblock %}
</head>

<body>

{% rgraph piechart %}

</body>
</html>

and this is the template for my new tag

{% extends "django_rgraph/rgraph_base.html" %}

{% block rgraph_chart %}
<script>
window.onload = function() {
    var {{ chart.name }} = new RGraph.Pie('{{ chart.name }}', [{% for value in chart.values %}{{ value }}{% if not forloop.last %},{% endif %}{% endfor %}]);
    {% for option, value in chart.options.items %}
    {{ chart.name }}.Set('{{ option }}', {{ value }});
    {% endfor %}

    {% if chart.animate %}
    RGraph.Effects.Pie.RoundRobin({{ chart.name }});
    {% else %}
    {{ chart.name }}.Draw();    
    {% endif %}
}
</script>
{% endblock %}

and for completeness, rgraph_base.html looks like this

{% block js.custom %}
{% for js in chart.js %}
<script src="RGraph/js/{{ js }}"></script>
{% endfor %}
{% endblock %}

{% block rgraph_chart %}Insert Chart Here{% endblock %}

I would expect this to create an html page where the javascript gets included in the header, but instead it appears in the body, like this

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title>Test Charts</title>
</head>

<body>

<!-- I was expecting these script tags to be below the title tag -->
<script src="RGraph/js/RGraph.common.core.js"></script>
<script src="RGraph/js/RGraph.common.tooltips.js"></script>
<script src="RGraph/js/RGraph.common.effects.js"></script>
<script src="RGraph/js/RGraph.pie.js"></script>

<script>
window.onload = function() {
    var pie1 = new RGraph.Pie('pie1', [10,24,15,82]);
    pie1.Set('chart.gutter.left', 30);
    pie1.Draw();
}
</script>
</body>
</html>

With this setup, with a template in the new tag overriding the block defined in the top level template, should I be able to have the scripts appear in the top head tag?

Upvotes: 0

Views: 734

Answers (1)

Issac Kelly
Issac Kelly

Reputation: 6359

Akonsu is right, you have a misunderstanding of django template tags, they can't override other blocks.

Upvotes: 1

Related Questions