2013-04-10 2 views
9

나는 내 HTML 소스에 <template> 태그를 사용하기 위해 노력하고있어이 상황이있어 :HTML 템플릿 태그와 JQuery와

<template id="some-id"> 
    <div id="content-container"> 
    <span>{{some_string}}</span> 
    <div> 
</template> 

이 문서에서 템플릿을 배치 끝을 있지만 간주되지 않습니다 DOM에 있어야합니다. 즉, $ ("# content-container")는 템플릿 태그를 지원하는 브라우저에서 찾을 수 없습니다. 내가 검색하는 경우 :

$("#some-id") 

나는이 다시 얻을이의

<template id=​"some-id">​ 
    #document-fragment 
    <div id="content-container"> 
     <span>{{some_string}}</span> 
    <div> 
</template>​ 

아무도 나를 놀라게하지 않습니다. 내가해야할 일이 무엇인지 알아야 할 것은 문서 조각의 내용을 복제하고 내가 원하는 곳에 DOM을 사용할 수있는 새로운 노드를 만드는 것이다.

이 작업을 수행하는 방법에 대한 예제가 jQuery 승격되었지만이 항목을 둘러싼 많은 코드는 이미 jQuery를 사용하고 있으며 jQuery를 사용하여이를 수행하는 방법을 알아야합니다.

stuff = $("#some-id").html() 
new_node = $(stuff) 

이 다음과 같은 오류 결과가 :

Error: Syntax error, unrecognized expression: <the html string> 

내가 알고하지 않습니다

내 첫번째 생각은 새로운 노드를 작성하는 데 사용할 다음 HTML을 얻을하는 것이 었습니다 오류는 콧수염 구문에 의해 발생합니다. 어딘가에이 동작에 대한 jQuery 솔루션이 있어야한다는 것을 알았지 만 Google로 검색 할 때 jQuery 템플릿에 대한 적중 횟수가 crapload로 달라집니다.

생각이나 답변 또는 사이트/페이지로 연결되는 포인터가 있습니까? 나는 마구 잡는 무언가를 함께 껴안는 것을 피하려고 노력하고있다.

편집 : 나는이 솔루션을 찾지 못했습니다. (여전히 솔루션인지 확인하기 위해 테스트하고 있지만 유망 해 보입니다).

template = $("#some-id") 
content = template.html() 
new_div = $("<div></div>") 
new_div.html(content) 

이전에 실제로 필요하지 않은 div가 포함 된 결과로 끝나지만 나는 그걸로 살 수 있습니다. 그러나 이런 종류의 kludgy 느낌. 누구든지 이것에 대해 더 나은 접근법을 가지고 있습니까? 위쪽은 아직 템플릿 태그 동작을 완전히 적용하지 않은 브라우저에서도 작동한다는 것입니다.

감사합니다.

+0

'$ ("# 일부-ID") html'는'해야 $ ("# some-id"). html()' – Nope

+0

죄송합니다, 예, 내 질문에 오타입니다. 내가 고칠거야. – jaydel

+0

jquery .clone보세요 ^^ http://api.jquery.com/clone/ – azzy81

답변

13

시도 :

var myTemplate = $("#some-id").html().trim(); 
var myTemplateClone = $(myTemplate); 
+0

도움을 주셔서 감사합니다 - 손질 - 내가 필요로하는 것! – Ivan

+3

'trim()'이 작동하는 이유는 무엇입니까? – mopo922

+0

'trim()'이 필요 없습니다. 아무것도하지 않습니다. – JJJ

6

내가 템플릿 그들과 상호 작용하는 방법 그림자 DOM 작동 방법이 사이트는 설명 할 것이라고 믿는다. http://robdodson.me/blog/2013/08/27/shadow-dom-the-basics/

실제로 그림자 템플릿 노드를 복제하고 jquery를 사용하는 것조차 필요하지 않습니다.여기

가 보여주는 jfiddle입니다 그것은 : http://jsfiddle.net/dtracers/fhWc3/1/

HTML :

<div id = "hoster"> 
    <span class = "title">Title</span> 
    <span class = "id">51ab89af</span> 
</div> 

<template id = "im-a-template"> 
    <h1><content select =".title"></content></h1> 
    <h1>Class Id: <content select = ".id"></content></h1> 
    <input type="text" placeholder = "Name"></input> 
</template> 

자바 스크립트 :.

// find where you want to put your shadow dom in 
var host = document.querySelector('#hoster'); 

var root = host.createShadowRoot(); // create the host root 

var template = document.querySelector('#im-a-template'); 

// this is the node of the object you wanted 
var documentFragment = template.content; 

// this is a cloned version of the object that you can use anywhere. 
var templateClone = documentFragment.cloneNode(true); 

root.appendChild(templateClone); // this empty root now has your template 
이 이
+0

'content'태그 사용시 HTML5 사양에서 거부되었습니다. http://stackoverflow.com/questions/17170547/is-there-a-content-tag-in-html-or-what-is -이 - 남자 가르침. – NWeir

+1

이것은 여기에 설명 된 내용 태그와 다른 용도입니다. http://www.html5rocks.com/en/tutorials/webcomponents/template/ 콘텐츠 태그는 그림자 루트 외부의 정보를 그림자 루트 내부의 데이터로 투영하는 데 사용됩니다 – dtracers

관련 문제