Meteor的模板

新建一个项目Meteor

meteor create meteor-template

会生成三个文件:

meteor-template.css
meteor-template.html
meteor-template.js

这三个文件就是模板文件,.js文件是逻辑和数据控制文件,.css文件是样式文件。
访问.html文件会自动加载.js.css文件。

在HTML文件中使用Meteor模板

Meteor模板定义三个最高级别的标签<head> <body> <template>

    <head>
          <title>meteor-study</title>
    </head>
    
    <body>
        <h1>I am Meteor!</h1>
        {{> meteor_study}}
    </body>
    <template name="meteor_study">
        <h2>{{templateName}}</h2>
        {{#each languages}}
            <h3>{{name}}</h3>
        {{/each}}
    </template>

不用写<!DOCTYPE html>了,能省则省!
Meteor的模板可以自由的使用html标签比如上面的使用的<h1>标签。

在模板中使用逻辑

{{}}是模板语言,是安全的不会输出html标签
他具有以下常用的语法:

  • {{> meteor_study}}导入指定的模板

  • {{#each langages}} {{/each}}循环

  • {{#if done}}done{{else}}notdone{{/if}} if判断

  • 等…
    详细的说明可以参考

给模板中的变量赋值

MVC的模式中可以在Controller层给View层赋值,在Meteor中也可以在.js文件中给模板赋值:

    if (Meteor.isClient) {
      Template.meteor_study.helpers({
          templateName:'Meteor Study',
          languages:[{name:'Node'},{name:'Meteor'},{name:'html'},{name:'css'}]
    
      });
    }

其中Meteor.isClient这句话判断是不是在客户端,在客户端就使用Template.meteor_study.helpers 给模板变量赋值。使用templateNamelanguages分别定义了一个字符串和一个数组。

使用css

.css文件负责控制样式,在meteor-template.css添加代码:

    body {
        font-family: sans-serif;
        background-color: #315481;
        background-image: linear-gradient(to bottom, #315481, #918e82 100%);
        background-attachment: fixed;
    
        position: absolute;
        top: 10px;
        bottom: 0;
        left: 10px;
        right: 0;
    
        padding: 0;
        margin: 0;
    
        font-size: 14px;
    }
    
    
    header {
        background: #d2edf4;
        background-image: linear-gradient(to bottom, #d0edf5, #e1e5f0 100%);
        padding: 20px 15px 15px 15px;
        position: relative;
    }
    
    h1 {
        font-size: 1.5em;
        margin: 0;
        margin-bottom: 10px;
        display: inline-block;
        margin-right: 1em;
    }

最终显示的效果:

《Meteor的模板》
代码地址:https://github.com/jjz/meteor…

    原文作者:姜家志
    原文地址: https://segmentfault.com/a/1190000003781596
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞