1

I have a Django template filter to retrieve dictionary items based on the key passed.

{% with data=dict_data|get_data:key %}

I have separately made a template_tag.py file which returns those items.

def get_domain_data(dictionary, key):
   p = ast.literal_eval(dictionary)
   return p[key]
# data being returned successfully

The issue is in passing the dynamic value of the key in the filter function.

   <script>
     var key_val = $('#input_id').val();
     '{% with data=dict_data|get_domain_data:"'+key_val+'" %}';  //encountering error here
            // rest of the code
     '{% endwith %}';
    </script>

If I hardcode a string value the entire operation works, but I am unable to use the JavaScript variable within the Django {% filter %} function.

halfer
  • 19,824
  • 17
  • 99
  • 186
Simran
  • 593
  • 1
  • 14
  • 37
  • 1
    The template code is run before the javascript is. This is inevitable, as the page is rendered from the template on the server and then sent to the client. The client runs the javascript once the page is ready on the client. So you can't use javascript to interact with the template like that. – Matt Ellen May 10 '19 at 11:02
  • 1
    You'll need to create a js callback that contacts the website and gets the required data with an xhr or some other system. – Matt Ellen May 10 '19 at 11:04

2 Answers2

2

As mentionned by Matt Ellen in a comment, the template code is executed on the server, then the generated result is sent to the browser which interprets the javascript parts - so this just can not work this way.

If your data dict is small enough and doesn't depend on javascipt user interactions (ie the javascript only reads it), then the solution is to serialize it to json (in the view itself or using a template filter - one might already exists FWIW), bind it to a javascript variable (in the template) and then let the javascript code use it as just any js object, ie (assuming a "jsonify" template filter):

 <script>
     var data_dict = {% data_dict|jsonify %};

     function do_something() { 
         var key_val = $('#input_id').val();
         var data = data_dict[key_val];
            // rest of the code
     }
     // and you'll probably want to bind do_something to
     // some js event handler
 </script>
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
-2

There is a similar issue at Get javascript variable's value in Django url template tag

Providing arg1 can be numeric and the reversed url doesn't contain other instances of the string /12345/ then you can use,

var url_mask = "{% url 'someview' arg1=12345 %}".replace(/12345/, tmp.toString());
Spangen
  • 4,420
  • 5
  • 37
  • 42