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

how to run a function inside a template

12 Answers 4410 Views
Templates
This is a migrated thread and some comments may be shown as answers.
Mike
Top achievements
Rank 1
Mike asked on 26 Apr 2012, 05:36 PM
I have a template that looks somewhat like this:

<script type="text/x-kendo-tmpl" id="thisTemplate"><div id="${data1}">
<div id="thisDiv" class="thisClass ${newClass}">
 ... Div content...
</div>
</script>

As I read in my data I would like to have ${newClass} be a string that is determined by a function:
 i.e.
if(condition A) {
${newClass} = "a string of text";
} else {
${newClass} = "a different string of text";
}

In essence, I want ${newClass} to be a string that is determined by a function.

Does anyone know how to do this...?

12 Answers, 1 is accepted

Sort by
0
Vladimir
Top achievements
Rank 1
answered on 03 May 2012, 09:04 AM
Very interesting, i want to know how do it, too

I take a value from json, and if value is not empty, i want to display link, another way - display simple text.

Also, how to hide button ({command}) on some rows, where some value is empty (or =other_some_value)?

Does anyone know how to do this?

====================================================================================
If interesting, we can use that code for first part of question.
But how to hide button ({command}) on some rows, where some value is empty (or =other_some_value)?
<script id="alert-template" type="text/x-kendo-template">
  
    # if (type == 'success'){ #
  
            <div class='alert-message success'>
                <a class="close" href="">x</a>
                <p>
                    #= message #
                </p>
            </div>
  
    # } else if (type == 'error'){ #
  
            <div class='alert-message error'>
                <a class="close" href="">x</a>
                <p>
                    #= message #
                </p>
            </div>
  
    # } #
  
</script>
0
Petyo
Telerik team
answered on 03 May 2012, 12:52 PM
Hi,

You can use regular javascript syntax to achieve the logic you need. For instance: 

# var foo; if (bar) { foo = "bar" } else { foo = "baz" } #
 
#= foo #

Greetings,
Petyo
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Jan
Top achievements
Rank 1
answered on 17 Aug 2012, 12:37 AM
I would like to know too....

if type can be 'Success' , 'SucCess' ... how to handle the condition syntax?


# if (type == 'success'){ #
  
            <div class='alert-message success'>
                <a class="close" href="">x</a>
                <p>
                    #= message #
                </p>
            </div>
  
    # } else if (type == 'error'){ #
  
            <div class='alert-message error'>
                <a class="close" href="">x</a>
                <p>
                    #= message #
                </p>
            </div>
  
    # } #
0
Atanas Korchev
Telerik team
answered on 17 Aug 2012, 07:01 AM
Hi Jan,

You can always use || in the if statement:

# if (type == 'success' || type == 'Success')  { #

or you can just call toLowerCase():

# if (type.toLowerCase() == 'success') { #

Regards,
Atanas Korchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Jan
Top achievements
Rank 1
answered on 17 Aug 2012, 07:20 AM
Yes. the tolowercase() work when the template is defined in the same file.
But, when I load the template from external file. It won't work.
Please see my question at : http://www.kendoui.com/forums/framework/mvvm/mvvm-and-external-template.aspx#2235630 

I would appreciate it very much.
0
Atanas Korchev
Telerik team
answered on 17 Aug 2012, 07:31 AM
Hi,

 Your template is not executed with the right data. Please call the template function with your actual data.

Regards,
Atanas Korchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Jan
Top achievements
Rank 1
answered on 17 Aug 2012, 07:35 AM
Thank you for the quick reply,
please suggest me how to call the template with my data.
Since the data is MVVM....
I am not sure if I understand you correctly.
0
Atanas Korchev
Telerik team
answered on 17 Aug 2012, 07:50 AM
Hi,

 A template is a JavaScript function. Its only argument is the data which the template should work with:

var template = kendo.template("<strong>#= name #</strong>");

var templateData = { name: "John Doe" } ;

var html = template(templateData); 

console.log(html); //outputs "<strong>John Doe</strong>"

In a word you need to call your template function with the data it is supposed to process.

Regards,
Atanas Korchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Jan
Top achievements
Rank 1
answered on 17 Aug 2012, 08:02 AM
From the example you gave me, I already try. It works. The inline template works fine. no wonder about it.

However, I try to apply the template / MVVM

Like the scenario: I have "mydiv" connecting to data-template "my-template" and the data-bind to source.
the template was executed correctly when I bind mydiv and observable object0000

[1] at the beginning, I create an index.htm file, the template is also defined in the same file.
It works perfectly!!! but the problem is in the second part....

<div id="mydiv">
    <div id="listView" data-role="listview" data-editable="true" data-template="my-template"
         data-bind="source: MySource">
    </div>
</div>
 
<script id="my-template" type="text/x-kendo-template">
    <div>${Status}</div>
    <div>
      # if (Status.toUpperCase() == "SINGLE"){#
            <img src="imgs/black_acs.png" alt="black_acs image" />
      #}else if (Status.toUpperCase() == "MARRIED"){#
            <img src="imgs/blue_acs.png" alt="blue_acs image" />
      #}else if (Status.toUpperCase() == "OTHER"){#
             <img src="imgs/red_acs.png" alt="red_acs image" />
      #}#
    </div>
</script>
 
<script>
$(document).ready(function ()
            {
        var viewModel = kendo.observable({
           MySource: new kendo.data.DataSource({  // name and status
            transport: {
                      read: {
                        url: "http://xxx.com/REST.VN/GetData",
                        type: "GET",
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        data: function ()
                            {
                               var jsonParameters = {};
                                jsonParameters.parameter = "XXX";
                               return jsonParameters;
                            }
                }
             }
        });
 
    kendo.bind($("#mydiv"), viewModel);
});
 
</script>

The code above works fine.....


[2] ... after that, I decide to move the template as external file so that it can be reused by other pages.
I create another file called: template1.tmpl.htm 
I do not change anything in the template. Just copy and paste to another file. 

This is the content in the file. 

<script id="my-template" type="text/x-kendo-template">
    <div>${Status}</div>
    <div>
      # if (Status.toUpperCase() == "SINGLE"){#
            <img src="imgs/black_acs.png" alt="black_acs image" />
      #}else if (Status.toUpperCase() == "MARRIED"){#
            <img src="imgs/blue_acs.png" alt="blue_acs image" />
      #}else if (Status.toUpperCase() == "OTHER"){#
             <img src="imgs/red_acs.png" alt="red_acs image" />
      #}#
    </div>
</script>


In the index.html, I create a template loader function as suggested in http://docs.kendoui.com/howto/load-templates-external-files 
on the top of the page: <script src="templateLoader.js"></script>

At the script section, I modify:
<script>
 
$(document).bind("TEMPLATE_LOADED", function (e, data) {
                _itemTemplate = kendo.template($("#my-template").html(), { useWithBlock: false });
                _itemTemplate(data);
                bindMe(); 
            });
 
$(document).ready(function ()
           {
        templateLoader.loadExtTemplate("template1.tmpl.htm");
            });
 
function bindMe()
{
     var viewModel = kendo.observable({
           MySource: new kendo.data.DataSource({  // name and status
            transport: {
            read: {
            url: "http://xxx.com/REST.VN/GetData",
            type: "GET",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: function ()
                {
                    var jsonParameters = {};
                    jsonParameters.parameter = "XXX";
                return jsonParameters;
                }
            }
         }
    });
 
    kendo.bind($("#mydiv"), viewModel);
}
 
</script>


The result is not showing at all.....
I thought it is not loading the template, so I start debugging. The template is loaded.
(I won't think it is a data issue because it works fine when the template is on the same file.)


Then .... I think something might not correct in the template definition... (it should work fine since it works when template is on the same file)

removed every thing from the template file:

<script id="my-template" type="text/x-kendo-template">
    <div>fixed text</div>
</script>


This time ... it works with fixed text .... !?!? it becomes interesting....

Then, I start adding data to the template
<script id="my-template" type="text/x-kendo-template"> 
<div>${Status}</div> 
</script> 

Guess what !? ... it is not working ...
After trying ....
<script id="my-template" type="text/x-kendo-template"> 
<div>${data.Status}</div> 
</script> 
It works.... I am able to get the list of Status.

Why do we have to use "data." in the template (external template file)? Previously, the template is defined in the same file, I don't have to put .data in front of field name.
 
Now... conditioning ..
If I remove .toUpperCase(), it works. but I NEED to use the function (and other functions) in the if-else statements.
Since the data can be SiNgle, sinGLE etc.
Why it is not working when I exclude the template from the original file? 
<div>
                  # if (
data.Status.toUpperCase() == "SINGLE"){#
                        <img src="imgs/black_acs.png" alt="black_acs image" />
                  #}else if (
data.Status.toUpperCase() == "MARRIED"){#
                        <img src="imgs/blue_acs.png" alt="blue_acs image" />
                  #}else if (
data.Status.toUpperCase() == "OTHER"){#
                         <img src="imgs/red_acs.png" alt="red_acs image" />
                  #}#
        </div>
 


Please help .... 
I am totally new to the MVVM and the template. 
0
Atanas Korchev
Telerik team
answered on 17 Aug 2012, 08:09 AM
Hello Jan,

 As I said before your template is not executed with the right data:

$(document).bind("TEMPLATE_LOADED", function (e, data) {
                _itemTemplate = kendo.template($("#my-template").html(), { useWithBlock: false });
                _itemTemplate(data); // data is the argument of the callback not your view model
                bindMe();
            });

If you still need help I suggest you send us a complete sample which we can check locally.

Regards,
Atanas Korchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Justin
Top achievements
Rank 1
answered on 30 Sep 2013, 09:30 PM
How would you do it if you wanted the function to be in the viewModel as good OO practice?

We are trying to keep our templates light of logic.
0
Atanas Korchev
Telerik team
answered on 01 Oct 2013, 07:37 AM
Hello,

 This can be done only if the template is set via MVVM. Here is an example: http://jsbin.com/epaGAXu/1/edit

Regards,
Atanas Korchev
Telerik
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
Tags
Templates
Asked by
Mike
Top achievements
Rank 1
Answers by
Vladimir
Top achievements
Rank 1
Petyo
Telerik team
Jan
Top achievements
Rank 1
Atanas Korchev
Telerik team
Justin
Top achievements
Rank 1
Share this question
or