Table of Contents
Client Template
{{firstName}} {{lastName}}
grammar
表达式
高级表达式
将数据绑定到元素
了解模板
Home CMS Tutorial WordPress Embracing the Embers: Part 4

Embracing the Embers: Part 4

Sep 02, 2023 pm 08:37 PM

拥抱余烬:第 4 部分

In my previous tutorial, I introduced how to use Ember.Object to define models and work with datasets. In this section, we'll take a closer look at how Ember uses the Handlebars template framework to define your app's user interface.


Client Template

Most server-side developers are accustomed to using templates to define tags that will be dynamically populated. If you've ever used ASP.NET, ColdFusion, PHP, or Rails, you definitely know what I'm talking about.

JavaScript client-side templates have really started to gain popularity recently, especially because of its focus on building more desktop-like experiences. This means that more processing is done on the client side, and data is primarily pulled through server-side API requests.

I remember writing about client-side templates not too long ago when the jQuery template plugin was first released. Nearly three years later, it's still the most read post on my blog, showing just how high interest in client-side templates is. Since then, many other frameworks have been released, providing rich features and supporting communities. Handlebars is one of the more popular options and is the framework chosen by the Ember project for its templating needs. This makes sense since Handlerbars was created by Ember.js co-founder and core team member Yehuda Katz. But please note that I'm not going to do a comparison between template frameworks, I'm going to focus strictly on Handelbars since that's what Ember.js uses by default.

In the previous article, I showed some very basic templates in code:

<script type="text/x-handlebars">
    <h2 id="strong-firstName-lastName-strong"><strong>{{firstName}} {{lastName}}</strong></h2>
</script>
Copy after login
Copy after login

Two things that stand out are the script tag's type declaration and the curly braces, which act as delimiters for expressions that Handlebars will act on. This is very typical syntax, which I will discuss in detail shortly, and which you will use consistently when building Ember templates.


grammar

Although Handlebars use special syntax, at the end of the day you're actually mostly using standard HTML markup. Handlebars are used to inject content into this tag to present the data to the user. It does this by parsing the delimited expression and replacing it with the data you asked Handlebars to use. For Ember, Handlebars provides hooks and Ember uses them. This data usually comes from your controller (remember, the controller acts as the interface to the model).

The first thing any template needs is a script tag definition. Most of you have probably defined script tags to load JavaScript libraries. In fact, you've already done this, loading Handlebars into your Ember project:

<script src="js/libs/jquery-1.9.1.js"></script>
<script src="js/libs/handlebars-1.0.0-rc.3.js"></script>
<script src="js/libs/ember-1.0.0-rc.1.js"></script>
<script src="js/app.js"></script>
Copy after login

Slightly different than using it to define templates. First, we specify the type attribute of "text/x-handlebars". The browser ignores this type, but leaves the text available for inspection and allows Ember to recognize the template within the application. Additionally, Ember uses a data attribute called "data-template-name" that Ember can use to associate specific parts of the application with templates. For example, the following declaration defines a template named "employee":

<script type="text/x-handlebars" data-template-name="employee">
...
</script>
Copy after login

When your application starts, Ember scans the DOM for type="text/x-handlebars, compiles the templates it finds, and stores them in a property of the Ember object , the property is named Ember.TEMPLATES and use it to find out what is rendered for a given route. This is why it is so important to follow Ember's naming convention. In the example above, this template will automatically be associated to the employee routes and controllers you create in your application. Again, I can't stress too much how these naming conventions will make your development easier.

Ember relies on the URL to determine the resources to use and the templates to render. Let's say you have a profile page with the URL "/profile". You'll have a resource called profile that will load resources specific to that URL (like a route object), and you'll also have a template with the same name. We reviewed defining resources and routing objects in Part 2 of the Ember series, so if you're not sure what I'm talking about, be sure to jump back there and refresh your knowledge.

When you visit that URL, Ember knows it needs to load these resources and parse the templates you defined. It does this through its naming convention, knowing that because you go to "/profile" it needs to load the resource defined in profile and render it named data-template-name=" profile" template.

  • Route: Profile Route
  • Controller: ProfileController
  • Template:Personal information (note lowercase)

Looking at the naming convention again, you'll see that routes, controllers, and templates are all tied together with the same URL name, but the template is spelled in lowercase. This allows Ember to manage everything behind the scenes without having to do a lot of wiring.

还需要注意的是,如果您声明的模板没有 data-template-name 属性,Ember 将假定它是应用程序范围的模板 - 通常用作站点范围模板来创建用户界面元素,例如页眉、页脚和导航。如果您没有为应用程序甚至资源(例如 URL)显式定义模板,Ember 会自动为您执行此操作,以确保应用程序的稳定性和一致性。


表达式

下一步是包含您的标记和用于表示数据的分隔表达式。表达式通过双花括号进行分隔,这使得它们可以通过从控制器传递的数据轻松识别和解析。这是一个例子:

<script type="text/x-handlebars">
    <h2 id="strong-firstName-lastName-strong"><strong>{{firstName}} {{lastName}}</strong></h2>
</script>
Copy after login
Copy after login

在这种情况下,{{firstName}}{{lastName}} 表达式将被 Ember 解析并替换为实际数据。此外,Ember 设置了观察者,以便当您的数据发生变化时,您的模板会自动更新,并将更新反映给应用程序的用户。

到目前为止,我已经向您展示了一个非常简单的示例,但要点是:

  • Ember 使用特殊的类型属性来定义模板。
  • 模板使用标准标记以及分隔表达式,这些表达式在客户端进行解析。
  • 这些模板具有 Handlebars 的完整功能集。
  • Ember 设置观察者来动态更新您的用户界面数据(当用户界面数据发生变化时)。

这为您构建用户界面的方式提供了很大的灵活性。让我们继续看看可用的功能。


高级表达式

请记住,Ember 利用了 Handlebars,因此您可以在此处访问其完整的表达式。为了使几乎任何东西变得有用,条件表达式是必须的;车把提供了相当多的选择。

假设我有一个如下所示的 JSON 数据集:

"items": [{
    "title": "Tearable Cloth Simulation in JavaScript",
    "url": "http://codepen.io/stuffit/pen/KrAwx",
    "id": 5592679,
    "commentCount": 20,
    "points": 127,
    "postedAgo": "1 hour ago",
    "postedBy": "NathanKP"
}, {
    "title": "Netflix now bigger than HBO",
    "url": "http://qz.com/77067/netflix-now-bigger-than-hbo/",
    "id": 5592403,
    "commentCount": 68,
    "points": 96,
    "postedAgo": "2 hours ago",
    "postedBy": "edouard1234567"
}
Copy after login

如果我想确保 title 数据可用,我可以使用 #if 表达式添加条件“if”语句:

{{#if item.title}}
    <li>{{item.title}} - {{item.postedAgo}} by {{item.postedBy}}</li>
{{/if}}
Copy after login

这会检查 item.title 是否未定义,并继续处理 titlepostedAgopostedBy 数据表达式的后续表达式。

由于该数据集包含多个“记录”,因此可以安全地假设我们可能希望循环 item 的每个元素。这就是 {{#each}} 表达式发挥作用的地方。它允许您枚举对象列表。因此,再次记住模板是标记和 Handlebars 表达式的组合,我们可以使用 #each 表达式来循环遍历 Ember 模型对象中可用的每个项目。请记住,Ember 模型是从控制器派生的,控制器通过 Ember 的命名约定与模板关联。

<ul>
    {{#each item in model}}
    {{#if item.title}}
        <li>{{item.title}} - {{item.postedAgo}} by {{item.postedBy}}</li>
    {{/if}}
    {{/each}}
</ul>
Copy after login

这会渲染出类似于以下内容的内容:

<ul>
<li>Tearable Cloth Simulation in JavaScript - 1 hour ago by NathanKP</li>
<li>Netflix now bigger than HBO - 2 hours ago by edouard1234567</li>
<li>Fast Database Emerges from MIT Class, GPUs and Student&#39;s Invention - 33 minutes ago by signa11</li>
<li> Connecting an iPad retina LCD to a PC - 6 hours ago by noonespecial</li>
</ul>
Copy after login

显着的优势是 Ember 隐含的观察者规范,它将在更新时更新您的数据。

如果您的条件表达式需要更复杂,您将需要创建一个计算属性。这允许您基于可以将复杂代码条件应用于数据的方法创建属性。假设我只想显示标题为“JavaScript 中的可撕裂布料模拟”的数据。我需要设置几件事:

  • 我需要一个计算属性来扫描每个项目并告诉我标题是否匹配
  • 我需要创建一个控制器,可供模板中枚举的每个项目使用
  • 我需要更新模板,以便它为每个项目使用此控制器

    我需要做的第一件事是创建新的控制器,它将包装循环的每个项目并在其中创建计算属性:

App.TitleController = Ember.ObjectController.extend({
    titleMatch: function() {
      return this.get(&#39;title&#39;) === "Tearable Cloth Simulation in JavaScript";
    }.property()
});
Copy after login

查看代码,我们对 Ember.ObjectController 进行子类化以创建控制器。这是控制器,它将包装模板中循环的每个项目。接下来,我们创建一个名为 titleMatch 的方法,它使用 get() 方法来拉回当前标题,将其与我定义的文本进行比较,然后返回一个布尔值。最后,调用 Ember property() 方法将 titleMatch 方法定义为计算属性。

完成此操作后,我们将更新模板的 {{#each}} 表达式,以使用我们创建的新控制器来表示每个项目。这是通过使用 itemController 指令来完成的。需要理解的关键一点是 itemController 是 Ember 中的一个关键短语,旨在将控制器与模板的项目关联起来。不要将其与实际的控制器名称混淆(就像我最初所做的那样)。控制器名称分配给 itemController,如下所示:

<ul>
   {{#each item in model itemController="title"}}
      {{#if titleMatch}}
        <li>{{foo.title}} - {{foo.postedAgo}} by {{foo.postedBy}}</li>
      {{/if}}
    {{/each}}
</ul>
Copy after login

同样,命名约定规定,在模板中分配名称时,我们使用小写。在本例中,我们将 TitleController 分配给 itemController

现在,当循环每个项目时,计算属性 titleMatch 用于评估标题并在匹配时显示数据。


将数据绑定到元素

创建动态模板不仅仅是吐出文本。有时,UI 的外观需要受到正在处理的数据的影响。显示图像或建立链接就是很好的例子。

将数据绑定到元素需要使用特殊的 Ember 助手来帮助定义属性的上下文,并确保在数据更改时正确更新属性。对于元素属性,{{bindAttr}} 帮助器用于填充属性的值。如果我们需要动态指定图像的 URL,我们将使用以下语法:

<img src="/static/imghw/default1.png"  data-src="logoUrl"  class="lazy"  {{bindAttr}} alt="Embracing the Embers: Part 4">
Copy after login

对于不接收值的属性也可以这样做,例如disabled

<input type="checkbox" {{bindAttr disabled="isAdministrator"}}>
Copy after login

在这种情况下, isAdminstrator 可以是基于控制器中的方法的计算属性,或者只是一个普通的对象属性,为您在定义禁用复选框的条件方面提供了很大的灵活性。这种灵活性也适用于定义类名。如果我想使用条件语句来定义是否应将类应用于我的元素,我可以使用以下代码:

<div {{bindAttr class="isUrgent"}}>
  Warning!
</div>
Copy after login

根据布尔状态,我的标记将是:

<div {{bindAttr class="is-urgent"}}>
  Warning!
</div>
Copy after login

对于 true 条件,或:

<div>
  Warning!
</div>
Copy after login

对于 false 条件。请注意,当我为该类指定 isUrgent 时,Ember 对该名称进行了 dasher 处理,并将该类呈现为 is-urgent。如果您希望根据结果指定自己的类,可以使用类似于三元语句的条件表达式:

<div {{bindAttr class="isUrgent:urgent:normal"}}>
Copy after login

这将根据 isUrgent 的条件值返回该类的 urgentnormal


了解模板

模板将成为用户界面的基础,因此花时间阅读 Ember 和 Handlebars 站点上的文档以充分了解它们的整体功能非常重要。即使您不使用 Ember,Handlebars 也是一个适合您日常使用的出色框架,并且值得投资学习如何使用它。

Gabriel Manricks 在 Nettuts+ 上编写了一篇关于 Handlebars 的精彩教程,您可以使用它来加快框架的速度。

The above is the detailed content of Embracing the Embers: Part 4. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners Apr 17, 2025 am 08:25 AM

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

How to get logged in user information in WordPress for personalized results How to get logged in user information in WordPress for personalized results Apr 19, 2025 pm 11:57 PM

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo();  function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

How to sort posts by post expiration date in WordPress How to sort posts by post expiration date in WordPress Apr 19, 2025 pm 11:48 PM

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

How to display query count and page loading time in WordPress How to display query count and page loading time in WordPress Apr 19, 2025 pm 11:51 PM

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

Can I learn WordPress in 3 days? Can I learn WordPress in 3 days? Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

See all articles