2013-07-18 23 views
1

我目前正在使用KnockoutJS及其內置的模板引擎。我想要做的是創建一個其他模板可以構建的主模板。有點像在.NET中的UserControl,但在HTML中。我該如何繼承HTML模板?

實施例:

<script id="ParentTemplate" type="text/html"> 
    <div class="Container"> 
     <div class="Header"> 
      <!-- Header Content Here --> 
     </div> 

     <div class="Separator></div> 

     <div class="Body"> 
      <!-- Body Content Here --> 
     </div> 

     <!-- more html here... --> 

     <div class="Footer"> 
      <!-- Footer content here --> 
     </div> 
    </div> 
</script> 

<script id="ChildTemplate" type="text/html"> 
    <div data-bind="{template: { name: 'ParentTemplate' }}"> 
     <header> 
      ... 
     </header> 

     <body> 
      ... 
     </body> 

     <footer> 
      ... 
     </footer> 
    </div> 
</script> 

請忽略的ChildTemplate的語法;我只是想說明發送零件到ParentTemplate

請注意:我正在構建一個純HTML/JQuery/KnockoutJS單頁面應用程序。沒有.NET/PHP /等。協助這些模板。

回答

1

看看DurandalJS的構圖。它是什麼,我認爲你正在努力實現

使用DurandalJs你將各個部分分離出來,成爲單獨的文件

Shell.html

<!DOCTYPE html> 
<html> 
    <head> 
    <!- usual content --> 
    </head> 
    <body> 
    <div data-bind="compose:'views/parent.html'"></div> 
    </body> 
</html> 

Parent.html大框架

<div class="Container"> 
    <div class="Header" data-bind="compose:'views/header.html'"></div> 

    <div class="Separator></div> 

    <div class="Body" data-bind="compose:'views/body.html'"></div> 

    <!-- more html here... --> 

    <div class="Footer" data-bind="compose:'views/footer.html'"></div> 
</div> 

我建議你看一下documenta重刑,因爲它是非常好,有一些已經建立

編輯
只是用淘汰賽 基礎幾個模板,你可以使用

的Javascript

var details = { 
    header: 'this is the Page header', 
    details: 'page details go here', 
    footer: 'something about the footer goes here' 
}; 

HTML模板

<script id="ChildTemplate" type="text/html"> 
    <div data-bind="template: { name: 'ParentTemplate', data: details }"></div> 
</script> 

<script id="ParentTemplate" type="text/html"> 
    <div class="Container"> 
     <div class="Header" data-bind='text: header'></div> 

     <div class="Separator></div> 

     <div class="Body" data-bind="text: details"></div> 

     <!-- more html here... --> 

     <div class="Footer" data-bind="text: footer"></div> 
    </div> 
</script> 

如果您的標題,細節和頁腳包含html標記,那麼我會建議將綁定從文本更改爲html,以便正確渲染。

+0

純粹的圖書館建議可能應該是一個評論。我想完整的答案將提供一個簡單的例子,說明如何真正實現OP的目標。 – millimoose

+0

是啊,夠公平的。我會盡量擴大答案。 –

+0

+1,用於向我介紹DurandalJS,但是這種解決方案迫使我將父母分成單獨的模板並稍後加入,而不是在子模板中注入部分的父模板。所以你最終只有兩個物理模板。這個解決方案最終有4個或更多。 – Laith