渲染模板(Rendering a Template)
优质
小牛编辑
135浏览
2023-12-01
路由用于将外部模板呈现到屏幕,这可以通过在路由处理程序中定义templateName来实现。
语法 (Syntax)
Ember.Route.extend ({
templateName: 'path'
});
例子 (Example)
以下示例显示如何呈现用于显示数据的模板。 创建前面章节中指定的新路由。 在这里,我们创建了路径作为帖子,并使用以下代码打开router.js文件以定义URL映射 -
import Ember from 'ember';
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config
//The const declares read only variable
const Router = Ember.Router.extend ({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
this.route('posts', function() {
this.route('new');
});
});
//It specifies Router variable available to other parts of the app
export default Router;
创建application.hbs文件并在其中添加以下代码 -
//link-to is a handlebar helper used for creating links
{{#link-to 'posts'}}Click Here{{/link-to}}
{{outlet}} //It is a general helper, where content from other pages
will appear inside this section
使用以下代码打开在app/routes/下创建的文件posts.js -
import Ember from 'ember';
export default Ember.Route.extend ({
templateName: 'posts/new'
});
使用以下代码打开在app/templates/下创建的posts/new.hbs文件 -
<h2>Posts</h2>
Page is rendered by defining templateName property.
{{outlet}}
输出 (Output)
运行ember服务器,您将收到以下输出 -
当您单击输出中收到的链接时,它将生成结果,如以下屏幕截图所示 -