简体   繁体   中英

How to inject JavaScript variable in a Django template filter

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.

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>

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM