2017-11-24 7 views
2

내 변수를 해당 템플릿에 전달하고 렌더링 한 다음 결과 HTML을 문자열로 가져 오려고합니다.AngularJS 템플릿을 문자열로 변환하려면 어떻게해야합니까?

AngularJS에서 어떻게 할 수 있습니까? render_to_string()function in Django과 유사한 기능이 있습니까?

문제는 내가 email.html 템플릿을 가지고 있다는 것입니다 (이메일을 레이아웃하는 것이 고통 스럽습니다). 변수를 채우고 싶습니다.

Let's는 email.html의 내용이 같은 STH 것을 asume :

<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> 

는 내가 객체가 있습니다

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

: data = {name: 'Foo', email: '[email protected]' }

그때에 STH 비슷한 기대를

결국이 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: [email protected]</div> 
    </body> 
</html> 

답변

1

당신은 당신의 HTML 프로그램 컴파일 시도 할 수 있습니다이 기능을 꽤 많이 할 수있는 볼 수 있습니다 볼 수 있습니다. 먼저 html, headbody 태그를 템플릿에서 제거하십시오. 필요하지 않습니다.

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

email.html는 템플릿을 컴파일하는 서비스 $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를 사용하여 템플릿을 가져 오기, 템플릿이이 끝날 때까지 기다려야 $timeout를 사용하고 newElem.html()를 사용 angular.element, $compile를 사용과 element을 만들 수 있습니다.

이 코드를 함수 또는 지시문 안에 넣습니다.

희망 하시겠습니까?

+0

'$ compile' 서비스가 올바른 방향입니다! 고마워요! – alamasfu10

0

귀하의 질문을 이해할 수 있는지 확실하지 않지만 이것이 도움이된다고 생각됩니다.

그래서 일부 변수를 템플릿에 표현하고 렌더링하려고합니다. 내가 당신을 이해한다면 이것은 문자열 포맷과 비슷하게 들린다. AngularJS에서는 템플릿 리터럴이라는 것을 사용할 수 있습니다. 비록 JavaScript 사양이 도입 된 것이 확실하지 않더라도 ES2015 이상이 필요하다고 생각됩니다. 리터럴

당신은 이런 식으로 뭔가를 정의 할 수 있습니다

let name = 'Bob'; 

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

당신은 캐릭터가 초기화로 렌더링되는 식으로 이름을 사용했다.

\ n 또는 + 문자열을 함께 연결하는 데는 여러 줄의 문자열을 사용할 수도 있습니다.

편집 : 이것에 대해 더 많은 것을 위해 당신은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

당신은 당신이

+0

답변 해 주셔서 감사합니다! 나는 그것을 명확하게하기 위해 나의 질문을 편집했다. 나는 문자열 형성에 대해 알고있었습니다. 그것은 작동 할 것이지만, 포함시키고 자하는'html' 콘텐츠는 거대합니다. 이메일 템플릿 레이아웃이 얼마나 고통 스럽는지 아실 것입니다. – alamasfu10

관련 문제