Jesse Smith
Jesse Smith

Reputation: 963

Kendo template conditional formatting

Disclaimer: This was originally posted to the KendoUI forums, but has received no answers.

I'm trying to use conditional formatting of elements in my ListView's template. This partial view uses a shared DataSource to allow navigation via Pager, a two-card ListView, and the aforementioned template. Here's the relevant template code:

<script id="contact-template" type="text/x-kendo-template">
<div id="ContactCard" class="IsActive${IsActive}">
    #if (Salutation === null || Salutation === '') {#<h4>#}else{#<h4>#=Salutation# #}##=FirstName# #=LastName#</h4>
    #if (Title === null || Title === '') {##}else{#<p>#=Title#</p>#}#
    <br />
    #if (Email == 0 || Email === '') {##}else{#<p><a href='mailto:#=LastName#,%20#=FirstName#%20<#=Email#>'>#=Email#</a></p>#}#
    #if (Phone === null  || Phone === '') {##}else{#<p>#=Phone##if (Extension === null || Extension === '') {#</p>#}else{# ext. #=Extension#</p>#}##}#
</div>

I've tried several different ways of generating this code, including a simple if with inverted checks like if (Salutation != null && Salutation != '') but to no avail. I think I'm missing something about how to reference a DataSource's data from within the #if section? I tried something like if (#=Salutation# != null && #=Salutation# != '') but that threw a bad template error.

Here's the output:

output

Note: disregard the horrible formatting. This is pre-styling.

Here's the whole file, for reference:

@model int   @* accountId  *@

<article id="contactArticle">
    <div id="contactList"></div>
    <footer><span id="pagerTotal"></span><a href="#" class="k-link" id="pageLeft" onclick="pageLeftOne()"><</a><div id="pager"></div><a href="#" class="k-link" id="pageRight" onclick="pageRightOne()">></a></footer>
</article>
<script id="contact-template" type="text/x-kendo-template">
    <div id="ContactCard" class="IsActive${IsActive}">
        #if (Salutation === null || Salutation === '') {#<h4>#}else{#<h4>#=Salutation# #}##=FirstName# #=LastName#</h4>
        #if (Title === null || Title === '') {##}else{#<p>#=Title#</p>#}#
        <br />
        #if (Email == 0 || Email === '') {##}else{#<p><a href='mailto:#=LastName#,%20#=FirstName#%20<#=Email#>'>#=Email#</a></p>#}#
        #if (Phone === null  || Phone === '') {##}else{#<p>#=Phone##if (Extension === null || Extension === '') {#</p>#}else{# ext. #=Extension#</p>#}##}#
    </div>
</script>
<script type="text/javascript">
    var currentPage = 1;
    var pages;
    var contactDataSource;

    //SNIP//   

    $(document).ready(function() {
        var init = 1;
        contactDataSource = new kendo.data.DataSource({
            transport: {
                read: {
                    url: '@Url.Action("ContactPager", "Contact")',
                    dataType: "json",
                    type: "POST",
                    timeout: 2000,
                    data: {
                        accountId: @Model
                    }
                }
            },
            schema: {
                data: "data",
                total: "total",
                type: "json",
                model: {
                    fields: {
                        Id: { type: "string"},
                        FirstName: { type: "string" },
                        LastName: { type: "string"},
                        Title: { type: "string", defaultValue: ''},
                        Salutation: { type: "string", defaultValue: ''},
                        Extension: { type: "string", defaultValue: ''},
                        Phone: { type: "string", defaultValue: ''},
                        Email: { type: "string", defaultValue: ''},
                        IsActive: {type: "boolean"} //,
                        //ReceivesDistributionEmails: {type: "boolean"}
                    }
                }
            },
            pageSize: 2
        });

        contactDataSource.read();

        contactDataSource.bind("change", function(e) {
            if (init) {
                init = 0;
                if (contactDataSource.total() < 1) {
                    //SNIP

                } else {
                    $("#pager").kendoPager({
                        dataSource: contactDataSource,
                        buttonCount: 5
                    });
                    //SNIP//     
                    pages = $("#pager").data("kendoPager").dataSource.totalPages();

                    $("#contactList").kendoListView({
                        dataSource: contactDataSource,
                        pageable: true,
                        template: kendo.template($("#contact-template").html())
                    });
                    kendo.init($("#contactList"));
                }
            }
        });
    });

</script>

TL;DR: How do I get a Kendo template to build it's content based on the value of the datasource members?

Upvotes: 20

Views: 41347

Answers (4)

iDubrovinsky
iDubrovinsky

Reputation: 75

I realize this is an old thread however my answer may be useful to someone.

You can chain your conditionals inline like so:

groupHeaderTemplate: "${ value == 'D' ? 'Declined' : value == 'P' ? 'Pending' : value == 'A' ? 'Approved' : value }"

Upvotes: 1

gmakrygiannis
gmakrygiannis

Reputation: 360

For a shortcut you can just use:

# if(property){ #
#: property #
# } #

If you want to show/hide depending on the value (not empty string or null)

Upvotes: 1

Christian Phillips
Christian Phillips

Reputation: 18749

I know this is old, but another solution I have used is the following:

@(Html.Kendo().Grid<Object>()
    .Name("dataGrid")
    .DataSource(ds =>
        ds.Ajax()
            .Read(r => r.Action("Action", "Controller", new { area = "area" }))
            .ServerOperation(true)
            .PageSize(50)
            )
    .Columns(cols =>
    {
        cols.Bound(t => t.Property);
    })
    .Resizable(resizeable => resizeable.Columns(true))
    .Scrollable(t => t.Virtual(true))
    .Sortable()
    .Filterable()
    .ColumnMenu()
    .HtmlAttributes(new { style = "height:98%;width:100%;", @class="cssClass" })
    .Events(e => e.DataBound("onDataBound"))
    .Deferred()
    .ClientRowTemplate("<tr>" +
            "#=checkNull(Property)#" +
            "</tr>")
 )

Then, you can add a JavaScript function to check the property.

   function checkNull(item) {
        return item === null ? "" : item;
    }

It was quite frustrating, so it might help someone else. Obviously, you can alter the function to check for whatever you like.

Upvotes: 4

Igorrious
Igorrious

Reputation: 1618

Try wrapping the null in single quotes:

...
#if (Title != 'null' && Title != '')  { #
     <p>#=Title# </p> 
# } #
...

This notation can be used as an alternative although the tags are left behind. It could work depending on what kind of format you are trying to achieve.

<p>${ Title != 'null' && Title != '' ? Title : ''} </p>

Upvotes: 29

Related Questions