thatzprem thatzprem - 1 year ago 37
AngularJS Question

Unable to provide image names dynamically to {% static " in AngularJS

<div class="container" ng-repeat="item in itemslist">
<img ng-src="{% static "img/new/item.imagename" %}" alt="" />

item - > is an object, below is the object definition

var firstItem = {}; = 0; = "testfirstname";
firstItem.imagename = "cart.png";

var secondItem = {}; = 2; = "testsecondname";
secondItem.imagename = "home.png";

itemslist- > [firstitem, seconditem]

In the runtime, item.imagename is not getting replaced by its value (cart.png). coming out of the iteration. The request still looks with the variable name (item.imagename) and not the value (cart.png).

Page not found (404)

How do I get this working?

Answer Source

The order in which a page renders with Django is:

  1. A request is made from the client (browser) to the server (ultimately Django).

  2. Django matches a view using the url, and from the view renders the template in server.

  3. The client gets the response and renders the page. At this stage, the client knows nothing about Django, its templating system etc.

Angular is a JS technology that operates client-side. It has absolutely no way to know about static files, Django templates etc.

Therefore, if you require to load an image in client-side, then you have to properly specify the url beforehands. Since you know the name, you need only to provide the rest of the url to angular.

To do that, you need to include settings.STATIC_URL to your context, and render it into a js variable in your template. This variable will travel through to client, and then in angular use it to properly build the url.

Be sure to take care of angular's security considerations about interpolation though, but that's a different matter entirely.

The server-client confusion is a common one when beginning web development.