1

I want something like this inside django template. I want to use these variables in javascript file or another template file.

   {% set titles = {
      'table': form._meta.model._meta.verbose_name_plural.title(),
      'form': form._meta.model._meta.verbose_name.title()
       }
   %}

   {% set dtable = "dt_" + page %}

How can I create "set tag" in django template? Your answer would be helpful for me.

Hasan
  • 878
  • 1
  • 8
  • 19

2 Answers2

3

Although I think this is generally to be avoided (mixing template & logic is generally advised against in django), it appears this is possible through the use of the with tag.

{% with name="World" greeting="Hello" %}     
<html>
<div>{{ greeting }} {{name}}!</div>
</html>
{% endwith %}

In javascript, it would probably look like this

$(document).ready(function(){ 
   {% with greeting="hello" %}
      var text = '{{ greeting }}'
   {% endwith %}

});

There are some constraints, I don't believe you can set tuples or dictionaries this way. That said, if you're trying to set more complex types using {% with ... %} that logic should probably be handled in the view.

Referenced from this SO question.

rob
  • 2,119
  • 1
  • 22
  • 41
  • Thanks. But is there any customized way to use "set tag"? – Hasan Oct 11 '17 at 16:27
  • I don't understand your question. What is the differentiator between this and "set tag"? Also, why would you want to set tags in a template and not in a view if they're going to be used in logic? If you're trying to use a template tag through many pages you should use a context processor. I don't think you can create a tag in the template and proliferate to many pages without some very un-djangoistic javascript glue. – rob Oct 12 '17 at 12:12
1

CASE 1:

If you want to access your dictionary in the HTML template. You can pass titles dictionary to the template and access any key of the dictionary by the dot (.) operator.

<div class="something1">{{ titles.table }}</div> <div class="something2">{{ titles.form }}</div>

CASE 2:

If you want to send a dictionary to the HTML template and access in your javascript file, I would suggest you to store them in a data attribute of an input (hidden) element or any element and then access via javascript.

<input type="hidden" id="my-data-table" data-table="{{ titles }}">

You can access dictionary in your javascript file like this,

var myTitles = document.getElementById("my-data-table"); var titles = myTitles.getAttribute("data-table");

Akshay Suresh
  • 373
  • 1
  • 3
  • 9
  • Thanks. But, you have not got my question. I want to know how to create set tag in django template. – Hasan Oct 09 '17 at 01:33