我已经使用jTemplates有一段时间了,并试图完全使用jQuery + jTemplates + Web Services来构建一个站点。事情一直很顺利,直到我偶然发现了这样一种情况:我需要添加一些服务器控件,或者需要在模板呈现过程中使用code block <%= DoSomething(param) %>从代码后台解析一些数据。
考虑下面jTemplates的精简版本:
<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>现在我因为没能做到像这样简单的事情而感到头破血流。是不是我错过了什么?或者,jTemplates真的应该只用于呈现简单的HTML布局吗?模板引擎是否能够解析服务器代码块?或者我只是注定要死?
发布于 2012-05-04 14:31:42
这就是我最终得到的结论:
<p>Vendor Name: <span class="vendor-name" vid="{$T.VendorId}"></span></p>我没有尝试在呈现过程中执行服务器代码(这是不可能的),而是在占位符<span>上呈现id,然后使用jQuery注入值。
// After template is rendered
$.each($(".vendor-name"), function(){
$this = $(this);
var vid = $this.attr("vid");
$this.append("<%= GetVendorName(" + vid + ") %>")
});Hacky,但至少它可以工作;)
https://stackoverflow.com/questions/9232831
复制相似问题