templates tags works in scripts sections of the html?

39 views
Skip to first unread message

dk

unread,
Mar 20, 2015, 5:59:30 PM3/20/15
to django...@googlegroups.com
I am trying to create an autocomplete tag with jquery UI



in my view I got a list of commands,   in the meant time I am just testing it, so I have a list with ["a", "aaa", "b", "bbb"]
<script>
 $(function() {
 var avaibleTags = [
      {% for i in list_commands %}
          {{ i }}
      {% endfor %}

 ];
 $( "#tags" ).autocomplete({
  source: avaibleTags
 });
});
</script>

but it doesn't work,   does the string replacement of the template tags works on the script part ?  or I might be missing something?  thanks =)

Stephen J. Butler

unread,
Mar 20, 2015, 6:14:39 PM3/20/15
to django...@googlegroups.com
They do work. But did you check the generated page? I bet you get an
error in your browser's JavaScript console about syntax.
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/09c05edc-dd45-4c66-bae1-e30cd3bbdbf6%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Vijay Khemlani

unread,
Mar 20, 2015, 7:23:07 PM3/20/15
to django...@googlegroups.com
It works, but the javascript you are generating has syntax errors.

For example, you are missing the commas after every element.

Either way, dumping variables directly from django templates to JavaScript is not very elegant, you could make a JSON object in the view beforehand

json_tags = json.dumps(list_commands)

and then ouputting them in the template

var avaibleTags = {{ json_tags|safe }}

dk

unread,
Mar 23, 2015, 10:59:27 AM3/23/15
to django...@googlegroups.com
AHHH....!!!...
that make scenes  that the java script did work when I did it manually.   I haven't use json files before, so I am not  sure how to manage that, I will look around for more information on that.

Vijay Khemlani

unread,
Mar 23, 2015, 11:05:53 AM3/23/15
to django...@googlegroups.com
JSON is literally the notation for objects and arrays in JavaScript, when you "print" it it outputs valid JavaScript code.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
Reply all
Reply to author
Forward
0 new messages