2013-01-24 44 views
3

我想用流星模板填充script type="text/html標記。流星模板內部腳本標記

所以,這是一件很奇怪的事情,我知道。我想這樣做的一半原因是因爲Cloud9無法分辨JS腳本標記和HTML腳本標記之間的區別,並且當您嘗試在script標記中編寫HTML時,它的語法突出顯示和標記完成中斷。我的另一半隻是好奇,看看這是否可能,因爲存在一個醜陋的罪過解決方法。

所以這個:

<body> 
    <script type="text/html" id="test"> 
     {{> test}} 
    </script> 
</body> 

<template name="test"> 
    <span>Test</span> 
</template> 

產生以下:

<script type="text/html" id="test"> 
    <!--label:YRgyaMH8--> 
</script> 

任何人有辦法,迫使它呈現模板,而不是什麼樣子評估名稱作爲評論?

+0

您對此的最終目標是什麼?它是否有一個可供其他JS組件用來控制的模板?我問b/c還有其他方法可以將模板從HTML傳遞到JS,而不必將其嵌入到腳本標記中。例如,看看這篇文章: http://www.nczonline.net/blog/2011/10/11/simple-maintainable-templating-with-javascript/ – klamping

+0

我的最終目標是利用Cloud9用於編寫HTML的IDE功能,以維護將由Knockout使用的模板。 Knockout有一個使用[外部模板引擎](http://knockoutjs.com/documentation/template-binding.html)的方法,但是它很麻煩並且犧牲了在IDE中將模板編寫爲HTML的優點。因爲我已經在使用Meteor,所以我認爲使用它的「模板」系統將正常的HTML移動到腳本標記是非常好的,因爲Cloud 9會正常中斷,因爲它的「智能」足以知道腳本標記中的內容是的JavaScript。 – Tyrsius

+0

你有沒有考慮前面的淘汰賽和使用流星的約束力需求?我並不完全熟悉Meteor和Knockout的所有功能,但似乎它們在許多功能上重疊。 – klamping

回答

1

提交另一個答案b/c我想保留以前的記錄。我認爲這種方法會更好。

在你的html裏面,你要定義兩個部分。首先是你要放置你的模板代碼的地方。它會進入一個普通的div標籤內的評論。第二個是模板將放置在Knockout中消耗的位置。它看起來像這樣:

<template name="koTemplate"> 
    <div id="myTemplate"> 
     <span>Here is my template <a href="#">with children</a></span> 
    </div> 

    <script type="text/html" id="test"></script> 
</template> 
在客戶端JS代碼

然後,您要添加a callback to run when the template is rendered

Template.koTemplate.rendered = function() { 
    // Get the first node, then get the content inside of it 
    var templateHtml = this.firstNode.innerHTML; 

    // Remove the element so it doesn't get rendered 
    this.firstNode.parentNode.removeChild(this.firstNode); 
    // another option is to surround the contents inside the template w/comments, but that loses syntax highlighting 

    // Get the target node for placing the template in 
    var templateNode = this.lastNode; 

    // place the content from the original node to the target node 
    templateNode.innerHTML = templateHtml; 
}; 

這將基本上得到模板的內容,除去模板,然後將其放置在腳本標籤內。結果將如下所示:

<script type="text/html" id="test"> 
    <span>Here is my template <a href="#">with children</a></span> 
</script> 
+0

這會起作用,現在我可能會這樣做,但它有點麻煩。這也意味着該部分被模板改變了,因爲這段代碼處於被動狀態。理想情況下,我想找出Meteor內部在腳本標記內部顯示的內容,而不是真實的模板。改變這將是更清潔 – Tyrsius

+0

同意。流星文件仍然有點缺乏 – klamping

0

我建議您不要使用腳本標記,而應使用Cloud9不會將其視爲JS的其他通用標記,而Meteor也不會使用它。使用在我對這個問題意見的例子,它會是這個樣子:

<div id="template"> 
    <!--<span>test</span>--> 
</div> 

而在你的JS,你會解析:

var template = document.getElementById('template').firstChild.nodeValue, 
    result = parseTemplate(template, values); 

這是基本的想法。得到結果後,您必須將其轉換爲Knockout的模板解析。

+0

Knockout要求模板處於腳本標記中。 – Tyrsius

+0

這是一個黑客攻擊,但是能否在執行Knockout命令之前將模板寫入新的腳本標記? – klamping

+0

也許吧。我將不得不深入研究Meteor如何存儲模板。 – Tyrsius