views:

420

answers:

2

I've a template that looks like so:

<script type="text/html" id="TemplateEdit">

    <td>
        <input type="hidden" value="<#= item.ID #>" id="Edit.ID" name="Edit.ID" />
        <select id="Edit_ClientID" name="Edit.ClientID">
            <option value="1">test</option>
            <option value="2">test 2</option>
            <option value="3">test 3</option>
        </select>
    </td>
    <td>
        <select id="Edit_Frequency" name="Edit.Frequency">
            <option value="1">Daily</option>
            <option value="2">Weekly</option>
            <option value="3">Fortnightly</option>
        </select>
    </td>
</script>

In the "item" object that I'm passing in, it has some properties such as item.ClientID, and item.Frequency.

And a generic function handles sucking in the template and injecting it:

var template = tmpl(editTemplate, { item: data }); // this runs jresig's template code
domEle.append(template); //append the results in

Theoretically, after this code is run I could do something like:

$("#Edit_ClientID").val(data.ClientID);

However I don't want to burden this templating function with code specific for this templating exercise. This particular function handles templating for the entire site and I need to keep it generic.

Any ideas?

A: 

Why not pass the entire list of <Options> as a template parameter? Not necesarily the most elegant... but it would avoid adding conditional logic to the template (ie. "is this item the currently selected item? Yes output "selected", no output nothing).

+2  A: 

You can write normal javascript in there, so if I understand your question correctly, you can just do something like this:

<script type="text/html" id="TemplateEdit">

    <td>
        <input type="hidden" value="<#= item.ID #>" id="Edit.ID" name="Edit.ID" />
        <select id="Edit_ClientID" name="Edit.ClientID">
            <option value="1" <# if(data.ClientID == 1){ #> selected <# } #>>test</option>
            <option value="2"<# if(data.ClientID == 2){ #> selected <# } #>>test 2</option>
            <option value="3"<# if(data.ClientID == 3){ #> selected <# } #>>test 3</option>
        </select>
    </td>
    <td>
        <select id="Edit_Frequency" name="Edit.Frequency">
            <option value="1">Daily</option>
            <option value="2">Weekly</option>
            <option value="3">Fortnightly</option>
        </select>
    </td>
</script>

For executable javascript, use <# #>, rather than <#= #>

morgancodes