【问题标题】:How do you precompile jQuery templates in .Net?如何在 .Net 中预编译 jQuery 模板?
【发布时间】:2011-10-27 00:39:37
【问题描述】:

我正在使用 jQuery 模板来标记我的 JSON。我想知道是否有人有一个优雅的解决方案可以将它们预编译为服务器上的 javascript,以使浏览器不必每次都这样做。

我知道以下帖子:

pre-compile JavaScript templates to functions on project build

我知道我可以使用

https://github.com/wookiehangover/jquery-tmpl-jst

但我希望有更优雅的东西。例如,可以设置一个 HttpModule 来处理对 *.jst 文件的请求并编译它并返回结果 JS。

我不确定这是否存在,但假设是否可以让 jquery-tmpl-jst 项目在服务器端运行,那么构建 HttpModule 似乎相当容易。

感谢任何帮助。如果该模块不存在,如果我能弄清楚如何让实际编译工作,我会考虑编写它。

更新

我刚刚找到了这个库。它不是 HttpModule,但看起来它实现了 jQuery 模板编译服务器端。只是不确定它是否已完全实施。

https://github.com/awhatley/jquery-tmpl.net

更新

看起来上面的库实际上是在 .Net 中的服务器上执行 jQuery 模板,所以它永远不会将 javascript 转换为 jQuery 编译格式。有什么想法吗?

【问题讨论】:

    标签: jquery asp.net httpmodule jquery-templates


    【解决方案1】:

    第一个选项是使用 Cassette.Web (See documentation, get it with NuGet)。考虑到它还会为您的项目添加大约 6 个依赖包。我们不需要所有这些额外的东西,所以我们决定提取所需的部分,这是一项非常简单的任务:

    所以第二个选项

    1. 为 .NET 获取一些 JS 引擎(我们使用 Jurassic,就像 Cassette.Web 所做的那样)
    2. Download JS extract from jQuery-tmpl plugin 在 Cassette.Web 中使用。
    3. 在 JS 引擎中执行下载的 JS 文件。
    4. 在 JS 引擎中执行“buildTmplFn”JS 函数,将模板作为参数传递给它
    5. 哇啦,获取编译后的模板作为返回值。

    例子:

    using Jurassic;
    ...
    private static string CompileTemplates(string sourceDirectory)
    {
        var resultBuilder = new StringBuilder();
        var scriptEngine = new ScriptEngine();
    
        scriptEngine.Execute(Properties.Resources.jqueryTmplCompiler);
    
        var templates = Directory.GetFiles(sourceDirectory, "*.htm?");
        if(templates.Count() > 0)
        {
            foreach (var filePath in templates)
            {
                Console.WriteLine("Compiling " + Path.GetFileName(filePath));
                string templateText = File.ReadAllText(filePath);
                string templateName = Path.GetFileNameWithoutExtension(filePath);
                string precompiledTemplate = scriptEngine.CallGlobalFunction<string>("buildTmplFn", templateText);
                resultBuilder.AppendFormat("$.template('{0}', {1});\n", templateName, precompiledTemplate);
            }
            Console.WriteLine("Templates successfully precompiled.");
        }
        else
        {
            ErrorExit("No templates found in Source Directory " + sourceDirectory);
        }
    
        return resultBuilder.ToString();
    }
    

    本例假设第二步下载的JS文件存放在当前项目的资源中。

    干杯

    【讨论】:

    • 优秀。这正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多