【问题标题】:How can I turn an AngularJS template into a string?如何将 AngularJS 模板转换为字符串?
【发布时间】:2018-05-08 10:50:01
【问题描述】:

我想将我的变量传递到该模板中,让它呈现,然后将生成的 HTML 作为字符串获取。

如何在 AngularJS 中做到这一点?有没有类似render_to_string()function in Django的功能?

问题是我有一个email.html 模板(你知道,布局电子邮件很痛苦),我想用变量填充它。

假设email.html的内容是这样的:

<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>Hello {{ name }}</h1>
    <div>We will contact you soon in this email address: {{ email }}</div>
  </body>
</html>

我有一个对象:data = {name: 'Foo', email: 'foo@bar.com' }

然后我会期待类似于:

let messageBodyHtml = render('path_to_email.html', data)

最后,messageBodyHtml 将包含一个包含以下内容的字符串:

<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>Hello Foo</h1>
    <div>We will contact you soon in this email address: foo@bar.com</div>
  </body>
</html>

【问题讨论】:

    标签: javascript angularjs django render


    【解决方案1】:

    您可以尝试以编程方式编译您的HTML。首先,从模板中删除 htmlheadbody 标签,您不需要它们。

    email.html

    <h1>Hello {{ name }}</h1>
    <div>We will contact you soon in this email address: {{ email }}</div>
    

    使用服务$compile 编译您的模板。

    angular.controller('someController', ['$scope', '$compile', function($scope, $compile){
    
        var templateString = '<div ng-include="\'./email.html\'" ></div>';
        var newElem = angular.element(templateString);
    
        $compile(newElem)($scope); // or use $scope.$new()
    
        // use $timeout to wait until the $digest end and template is fetched/compiled
        $timeout(function(){
            // use .html() to get the final HTML
            console.log(newElem.html());
        });
    
    }]);
    

    使用ngInclude获取您的模板,使用angular.element创建一个element与您的模板,$compile它,使用$timeout等到结束,然后使用newElem.html()

    将此代码放在函数或指令中。

    希望对你有帮助

    【讨论】:

    • $compile 服务是正确的方向!非常感谢!
    【解决方案2】:

    我不确定我是否理解您的问题,但我相信这会有所帮助。

    所以你希望将一些变量表达到模板中并渲染它们。如果我理解你的话,这听起来几乎像字符串格式。在 AngularJS 中,您可以使用所谓的模板文字。我部分相信您将需要 ES2015 或更高版本,尽管我不完全确定引入了哪个 JavaScript 规范,因为它被称为其他规范。

    使用文字,您可以定义如下内容:

    let name = 'Bob';
    
    // Notice the use of backqoutes instead of standard quotation syntax
    let templateString = `<div class="content"> ${name} </div>`;
    

    您使用 name 作为表达式,该表达式将在字符串初始化时呈现。

    这也可以用于多行字符串,而不是痛苦的 \n 或 + 将字符串连接在一起。

    编辑:有关此内容的更多信息,您可以查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

    你会发现你可以用这个功能做很多事情

    【讨论】:

    • 感谢您的回答!我编辑了我的问题以使其更清楚。我知道字符串格式化。它会起作用,但我想包含的htmlcontent 很大,你知道电子邮件模板布局有多痛苦:)
    猜你喜欢
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    相关资源
    最近更新 更多