Razor 模板转 JavaScript 字符串
好吧,我已经成功了,但我不确定这是多么可怕的黑客攻击。谁能告诉我我所做的是否正确,为什么?
我需要在 Razor 和 JavaScript 之间共享一个模板,以便可以在服务器端和另一个客户端使用它。所以,这就是我所做的:
Func<dynamic, HelperResult> sampleTemplate =
@<span>Sample markup @item.Something</span>;
然后,我在视图中使用了我的模板,如下所示:
for(int idxSample = 0; idxSample < Model.Number; idxSample++) {
@sampleTemplate(new { Something = "" })
}
对于 javascript,我这样做了:
<script type="text/javascript">
var someJsTemplate = "" +
<r><[!CDATA[@sampleTemplate(new { Something = "" })]]></r>;
</script>
这样我以后就可以在需要时附加 someJsTemplate
。那么,判决结果是什么?有人看到更好的方法吗?或者这样可以吗?
编辑:
现在我无法使用它。虽然它在 FireFox 中运行良好,但 Chrome 不允许我进行 hack。有什么帮助吗?
Ok, I got this one working, but I'm not sure about how much of a terrible hack this is. Can anyone tell me if what I did is ok or not, and why?
I needed to share a template between my Razor and JavaScript, so one could use it server-side and the other client-side. So, here is what I did:
Func<dynamic, HelperResult> sampleTemplate =
@<span>Sample markup @item.Something</span>;
Then, I used my template in my View like this:
for(int idxSample = 0; idxSample < Model.Number; idxSample++) {
@sampleTemplate(new { Something = "" })
}
And for the javascript I did this:
<script type="text/javascript">
var someJsTemplate = "" +
<r><[!CDATA[@sampleTemplate(new { Something = "" })]]></r>;
</script>
So I could later append someJsTemplate
whenever I needed it. So, what is the verdict? Does anyone see a better way to do it? Or is this alright?
Edit:
Now I can't use this. Although it works fine in FireFox, Chrome does not allow my hack. Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对我来说,在服务器端代码中存储 HTML 看起来是个坏主意。就我个人而言,我会编写一个控制器:
和一个包含标记的部分(
~/Views/Shared/EditorTemplates/Item.cshtml
):然后,如果我需要在强类型视图中使用它,我只需使用编辑器模板:
在 javascript 中:
为了简化一点这个 javascript 调用,您可以编写一个助手:
然后:
Storing HTML in server side code looks like a bad idea to me. Personally I would write a controller:
and a partial (
~/Views/Shared/EditorTemplates/Item.cshtml
) containing the markup:Then if I need to use it in a strongly typed view I would simply use an editor template:
and in javascript:
And to simplify a little bit this javascript call you could write a helper:
and then:
这对我来说看起来不错。尽管我建议研究 @helper 语法,但这只会稍微改变模板的用法。
That looks good to me. Though I'd suggest investigating @helper syntax, which would only slightly change the usage of the template.