Search code examples
jqueryasp.netjtemplates

Server code block within jTemplates? Possible?


I've been using jTemplates for awhile, and trying to build a site completely with jQuery + jTemplates + Web Services. Things worked out really great until I stumbled upon a situation like this, where I need to add some server control or need to resolve some data from the code behind using code block <%= DoSomething(param) %> in the midst of template rendering.

Consider the stripped down version of jTemplates below:

<script type="text/html" id="ContentTemplates">
    {#template MAIN}
        {#foreach $T.Products as product}
            <div id="div-product-{$T.product.Id}" class="product-wrapper">
                {#include Content root=$T.product}
            </div>
        {#/for}
    {#/template MAIN}

    {#template Content}
        <div class="view-container">
            <p>Id: {$T.Id}</p>
            <p>Desc: {$T.Desc}</p>
            <p>Vendor Id: {$T.VendorId}</p>

            <!-- Vendor name doesn't supplied by the web service, 
                  it needs to be resolved using ASP.NET server code -->
            <p>Vendor Name: <%= GetVendorName({$T.VendorId}) %></p>
            <!-- i was hoping to do something like this, 
                  but apparently it wouldn't work this way -->
        </div>
    {#/template Content}
</script>

Now I'm banging my head on the wall for failing to achieve something as easy as this.. is it something that I've missed? or is it that jTemplates really should be used to render simple HTML layout only? Is the template engine capable of resolving server code blocks? Or am I simply just DOOMED?


Solution

  • This is what i ended up with:

    <p>Vendor Name: <span class="vendor-name" vid="{$T.VendorId}"></span></p>
    

    Instead of trying to execute server code in the midst of rendering process (which is not possible), I render the id on a placeholder <span>, then use jQuery to inject the value later.

    // After template is rendered
    $.each($(".vendor-name"), function(){
        $this = $(this);
        var vid = $this.attr("vid");
        $this.append("<%= GetVendorName(" + vid + ") %>")
    });
    

    Hacky, but at least it works ;)