Reputation: 55
This is my first time posting a question, so I will be as concise as possible.
I am trying to dynamically populate the HTML of a page upon log in. For the front end application I use Django + HTML & CSS. I want to dynamically add a 'li' item to an existing 'ul'.
The previous code, when the page was statically loaded was:
<ul id="marketplace-list">
<li id="shoes-marketplace-dropdown" class="dropdown dropdown-toggle">
<a href="{% url 'shoes_marketplace' %}">Shoes</a>
<ul class="dropdown-menu" role="menu">
<li><a href="{% url 'shoes_men' %}">Men</a></li>
<li><a href="{% url 'shoes_women' %}">Women</a></li>
</ul>
</li>
</ul>
When clicking the "Men" href, my browser would redirect to the following URL : http://localhost:9000/marketplaces/shoes/men/
Now I created a js variable with'li' tag having id 'shoes-marketplace-dropdown'.
I plan to dynamically add and create 'ul' tag with id 'marketplace-list dynamically' to the above tag in $(document).ready( function {...})
.
My approach is:
var shoes_market = " <li id=\"shoes-marketplace-dropdown\" class=\"dropdown dropdown-toggle\">" +
" <a href=\"{% url \'shoes_marketplace\' %}\">Shoes</a>" +
" <ul class=\"dropdown-menu\" role=\"menu\">" +
" <li><a href=\"{% url \'shoes_men\' %}\">Men</a></li>" +
" <li><a href=\"{% url \'shoes_women\' %}\">Women</a></li>" +
" </ul>" +
"</li>";
And in the $(document).ready() function I have:
$("#marketplace-list").prepend(shoes_market)
The HTML page builds correctly, but when I click the "Men" link, the following URL is seen in the browser:
http://localhost:9000/%7B%%20url%20'shoes_men'%20%%7D
The url is defined in urls.py as follows"
url(r'^marketplaces/shoes/men/$', views.shoes_men, name='shoes_men')
My guess is that, somehow the HTML code which contains url, placed in javascript as a string, does not get parsed through Django as defined in urls.py to it's associated value. Can you please help me? I have got no idea how to solve this out.
Thank you in advance!
Upvotes: 3
Views: 1060
Reputation: 717
The problem is occurring because your URL tag is in JS instead of HTML, and the Django template engine doesn't work on JS static files. If you really want to still continue with the JS implementation, then in HTML template create script tag with a variable
<script>
var men_shoe_link = {% url 'shoes_men' %}
</script>
And then you can use this variable in the JS, as your code is in $(document).ready() function, first your var will be created and then the JS file will be processing. So then in JS string now you can have
"<a href='${men_shoe_link}'>Shoes</a>"
Upvotes: 1