I want to build a menu where I can set one link highlighted using the {% block %} tag. I have something like this in my Javascript:
<loop>
$('#a-div').append('{% block ' + variable + ' %} <a href...</a> {% endblock %}')
<endloop>
In the source, this is displayed as “{% block Home %}”
How can I make JQuery not append this as a string but as a template tag?
You can’t. At least not without making an AJAX request to a Django template. In your case, it would be slow and make unnecessary extra requests. It’s just not worth it. You can insert snippets from Django templates via jQuery by using, for example, the jQuery
loadfunction. But you can’t replace a specific{% block %}tag, because by the time jQuery runs, the template has already been processed (and references to block tags removed). But this is not a situation where you should be doing that in any case.Why don’t you rather highlight the menu with a CSS class? Here is my usual solution to this problem:
base_extras.pyin one of yourtemplatetagsfolders. If you don’t have one, create one in an appropriate folder.Inside
base_extras.py, paste this code:Now, in your template, on your menus in your base template, do something like this:
This will make that the menu where your URL currently is has the
activeclass. Then, in your CSS, just add a special class for a menu item withactiveto look slightly different than the other menus.And if you happen to need to change the active menu with jQuery, you can just remove the
activeclass on all menus, and add it to the newly selected menus: