This is a migrated thread and some comments may be shown as answers.

Use JS Variable for Content

2 Answers 2422 Views
Templates
This is a migrated thread and some comments may be shown as answers.
Ashleigh L
Top achievements
Rank 1
Ashleigh L asked on 12 May 2015, 05:34 PM

I'm sure I'm missing something simple, but I can't seem to figure this one out.

Say I've got a template where I need to display the image for an object, and if the object has no image, display a default. I currently have this code inside my template: 

# if (data.Image.length > 0) { #
    <img src="/content/#= data.ID #/Image/#= data.Image #" class="img-responsive border-radius" />
# } else { #
    <img src="/content/default.jpg" class="img-responsive border-radius" />
# } #

Which works well, but I'm not thrilled w/ having to repeat the actual HTML image tag and classes - this is a small example, but what if I had a condition where there could be 10+ options for the image src?. Then I'd have the exact same HTML 10+ times.

I've tried creating a variable to hold the image source and then using that in the template, but this doesn't seem to work:

# if (data.Image.length > 0) {
    var image_var = "/content/#= data.ID #/Image/#= data.Image #"
}
else {
   var image_var = "/content/default.jpg";
}#
<img src="#= image_var #" class="img-responsive border-radius" />

The code above works for default image, but the src for the object with an image doesn't actually get the ID and image name values - this is what's in the src when the element is inspected:

/content/;$kendoOutput+='= data.ID ';/Image/;$kendoOutput+='= data.Image ';

Removing the "#= #" around the data just puts the "data.ID" text into the src:

/content/data.ID/Image/data.Image

2 Answers, 1 is accepted

Sort by
0
Alexander Popov
Telerik team
answered on 14 May 2015, 11:07 AM
Hello shimmoril,

You can avoid creating complex templates by using external JavaScript functions. For example: 
<script type='text/x-kendo-template'>
    <img src="#=getImageURL(data)#" class="img-responsive border-radius" />
</script>
<script>
  function getImageURL(data){
    //some logic
    return "some url generated in the getImageURL function";
  }
</script>

Regards,
Alexander Popov
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
0
Ashleigh L
Top achievements
Rank 1
answered on 14 May 2015, 03:52 PM
That works, thanks Alexander.
Tags
Templates
Asked by
Ashleigh L
Top achievements
Rank 1
Answers by
Alexander Popov
Telerik team
Ashleigh L
Top achievements
Rank 1
Share this question
or