Use JS Variable for Content

3 posts, 0 answers
  1. Ashleigh L
    Ashleigh L avatar
    113 posts
    Member since:
    Jun 2012

    Posted 12 May 2015 Link to this post

    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:


  2. Alexander Popov
    Alexander Popov avatar
    1411 posts

    Posted 14 May 2015 Link to this post

    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" />
      function getImageURL(data){
        //some logic
        return "some url generated in the getImageURL function";

    Alexander Popov
    Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
  3. Ashleigh L
    Ashleigh L avatar
    113 posts
    Member since:
    Jun 2012

    Posted 14 May 2015 in reply to Alexander Popov Link to this post

    That works, thanks Alexander.
Back to Top