Meteor:第一个 html 文件将被 iron-routing 加载

Meteor: which first html file will iron-routing load

我正在创建一个 Meteor 应用程序。第一次创建应用程序时,Meteor 将此示例代码放在 hello.html

<head>
  <title>hello</title>
</head>

<body>
  <h1>Welcome to Meteor!</h1>

  {{> hello}}
</body>

<template name="hello">
  Hello World Template
</template>

我安装 Iron-Router 包。然后这是我的 lib/Router.js 文件:

Router.route('/', function () {
    this.render('post_template');
});

这是我的 client/templates/posts/post_template.html

<template name="post_template">
   Example Template
</template>

我不知道为什么我 运行 这个应用程序。结果是:

HelloWorld Template
Example Template

换句话说,Meteor 的哪一部分配置加载 hello.html 作为默认页面,然后将所有其他模板附加到路由里面?

谢谢:)

IR 将附加到 <body>(如果存在)(否则会为您添加一个),因此建议您删除整个 <body> 标签。

您完全删除 hello.html 实际上是安全的(因为您也不需要 hello 模板)。如果要保留 head 标签,只需将文件修改为:

<head>
  <title>hello</title>
</head>

要了解为什么要包含 hello.html,请参阅文档的 Structuring your application 部分:

HTML files in a Meteor application are treated quite a bit differently from a server-side framework. Meteor scans all the HTML files in your directory for three top-level elements: <head>, <body>, and <template>. The head and body sections are separately concatenated into a single head and body, which are transmitted to the client on initial page load.

所以您的所有 html 文件总是包含在内。如果您不想包含它们,则需要将它们从您的应用中删除。

在这种情况下,第一个 Meteor 负载是

<body>
  <h1>Welcome to Meteor!</h1>

  {{> hello}}
</body>

因为您在那里调用了 hello 模板,所以这是您第一个出现在屏幕上的。

我建议在这种情况下使用 layout 模板并删除 <body> 标签

所以声明路由。

Router.configure({
 layoutTemplate:'layout'
})

删除 <body><head> 标签并放置此 layout template

<template name="layout">
 <navbar>
 <!-- This stuff will be available on all routes since you are declaring on the layout template -->
 </navbar>
   {{> yield}} <!-- this yield helper will render the post_template or any other -->
</template>

例如

如果你有这2条路线。

Router.route('/', function () {
    this.render('post_template');
});
Router.route('/example', function () {
    this.render('example');
});

这里发生了什么,当你通过 / 路线时,iron router 会将 'post_template' html 渲染到布局模板中,当你导航到 /example, iron router 会移除post_Template html 并渲染/example 模板内的内容,如果你想在所有页面上有相同的内容,在<layout> 声明它模板即 footersnavbars、等等

布局模板类似于此处的 "master" 模板。