亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Client Template
grammar
表達(dá)式
高級(jí)表達(dá)式
將數(shù)據(jù)綁定到元素
了解模板
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><strong>{{firstName}} {{lastName}}</strong></h2>
</script>

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>

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>

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 將假定它是應(yīng)用程序范圍的模板 - 通常用作站點(diǎn)范圍模板來創(chuàng)建用戶界面元素,例如頁(yè)眉、頁(yè)腳和導(dǎo)航。如果您沒有為應(yīng)用程序甚至資源(例如 URL)顯式定義模板,Ember 會(huì)自動(dòng)為您執(zhí)行此操作,以確保應(yīng)用程序的穩(wěn)定性和一致性。


表達(dá)式

下一步是包含您的標(biāo)記和用于表示數(shù)據(jù)的分隔表達(dá)式。表達(dá)式通過雙花括號(hào)進(jìn)行分隔,這使得它們可以通過從控制器傳遞的數(shù)據(jù)輕松識(shí)別和解析。這是一個(gè)例子:

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

在這種情況下,{{firstName}}{{lastName}} 表達(dá)式將被 Ember 解析并替換為實(shí)際數(shù)據(jù)。此外,Ember 設(shè)置了觀察者,以便當(dāng)您的數(shù)據(jù)發(fā)生變化時(shí),您的模板會(huì)自動(dòng)更新,并將更新反映給應(yīng)用程序的用戶。

到目前為止,我已經(jīng)向您展示了一個(gè)非常簡(jiǎn)單的示例,但要點(diǎn)是:

  • Ember 使用特殊的類型屬性來定義模板。
  • 模板使用標(biāo)準(zhǔn)標(biāo)記以及分隔表達(dá)式,這些表達(dá)式在客戶端進(jìn)行解析。
  • 這些模板具有 Handlebars 的完整功能集。
  • Ember 設(shè)置觀察者來動(dòng)態(tài)更新您的用戶界面數(shù)據(jù)(當(dāng)用戶界面數(shù)據(jù)發(fā)生變化時(shí))。

這為您構(gòu)建用戶界面的方式提供了很大的靈活性。讓我們繼續(xù)看看可用的功能。


高級(jí)表達(dá)式

請(qǐng)記住,Ember 利用了 Handlebars,因此您可以在此處訪問其完整的表達(dá)式。為了使幾乎任何東西變得有用,條件表達(dá)式是必須的;車把提供了相當(dāng)多的選擇。

假設(shè)我有一個(gè)如下所示的 JSON 數(shù)據(jù)集:

"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"
}

如果我想確保 title 數(shù)據(jù)可用,我可以使用 #if 表達(dá)式添加條件“if”語(yǔ)句:

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

這會(huì)檢查 item.title 是否未定義,并繼續(xù)處理 title、postedAgopostedBy 數(shù)據(jù)表達(dá)式的后續(xù)表達(dá)式。

由于該數(shù)據(jù)集包含多個(gè)“記錄”,因此可以安全地假設(shè)我們可能希望循環(huán) item 的每個(gè)元素。這就是 {{#each}} 表達(dá)式發(fā)揮作用的地方。它允許您枚舉對(duì)象列表。因此,再次記住模板是標(biāo)記和 Handlebars 表達(dá)式的組合,我們可以使用 #each 表達(dá)式來循環(huán)遍歷 Ember 模型對(duì)象中可用的每個(gè)項(xiàng)目。請(qǐng)記住,Ember 模型是從控制器派生的,控制器通過 Ember 的命名約定與模板關(guān)聯(lián)。

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

這會(huì)渲染出類似于以下內(nèi)容的內(nèi)容:

<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>

顯著的優(yōu)勢(shì)是 Ember 隱含的觀察者規(guī)范,它將在更新時(shí)更新您的數(shù)據(jù)。

如果您的條件表達(dá)式需要更復(fù)雜,您將需要?jiǎng)?chuàng)建一個(gè)計(jì)算屬性。這允許您基于可以將復(fù)雜代碼條件應(yīng)用于數(shù)據(jù)的方法創(chuàng)建屬性。假設(shè)我只想顯示標(biāo)題為“JavaScript 中的可撕裂布料模擬”的數(shù)據(jù)。我需要設(shè)置幾件事:

  • 我需要一個(gè)計(jì)算屬性來掃描每個(gè)項(xiàng)目并告訴我標(biāo)題是否匹配
  • 我需要?jiǎng)?chuàng)建一個(gè)控制器,可供模板中枚舉的每個(gè)項(xiàng)目使用
  • 我需要更新模板,以便它為每個(gè)項(xiàng)目使用此控制器

    我需要做的第一件事是創(chuàng)建新的控制器,它將包裝循環(huán)的每個(gè)項(xiàng)目并在其中創(chuàng)建計(jì)算屬性:

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

查看代碼,我們對(duì) Ember.ObjectController 進(jìn)行子類化以創(chuàng)建控制器。這是控制器,它將包裝模板中循環(huán)的每個(gè)項(xiàng)目。接下來,我們創(chuàng)建一個(gè)名為 titleMatch 的方法,它使用 get() 方法來拉回當(dāng)前標(biāo)題,將其與我定義的文本進(jìn)行比較,然后返回一個(gè)布爾值。最后,調(diào)用 Ember property() 方法將 titleMatch 方法定義為計(jì)算屬性。

完成此操作后,我們將更新模板的 {{#each}} 表達(dá)式,以使用我們創(chuàng)建的新控制器來表示每個(gè)項(xiàng)目。這是通過使用 itemController 指令來完成的。需要理解的關(guān)鍵一點(diǎn)是 itemController 是 Ember 中的一個(gè)關(guān)鍵短語(yǔ),旨在將控制器與模板的項(xiàng)目關(guān)聯(lián)起來。不要將其與實(shí)際的控制器名稱混淆(就像我最初所做的那樣)。控制器名稱分配給 itemController,如下所示:

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

同樣,命名約定規(guī)定,在模板中分配名稱時(shí),我們使用小寫。在本例中,我們將 TitleController 分配給 itemController

現(xiàn)在,當(dāng)循環(huán)每個(gè)項(xiàng)目時(shí),計(jì)算屬性 titleMatch 用于評(píng)估標(biāo)題并在匹配時(shí)顯示數(shù)據(jù)。


將數(shù)據(jù)綁定到元素

創(chuàng)建動(dòng)態(tài)模板不僅僅是吐出文本。有時(shí),UI 的外觀需要受到正在處理的數(shù)據(jù)的影響。顯示圖像或建立鏈接就是很好的例子。

將數(shù)據(jù)綁定到元素需要使用特殊的 Ember 助手來幫助定義屬性的上下文,并確保在數(shù)據(jù)更改時(shí)正確更新屬性。對(duì)于元素屬性,{{bindAttr}} 幫助器用于填充屬性的值。如果我們需要?jiǎng)討B(tài)指定圖像的 URL,我們將使用以下語(yǔ)法:

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

對(duì)于不接收值的屬性也可以這樣做,例如disabled

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

在這種情況下, isAdminstrator 可以是基于控制器中的方法的計(jì)算屬性,或者只是一個(gè)普通的對(duì)象屬性,為您在定義禁用復(fù)選框的條件方面提供了很大的靈活性。這種靈活性也適用于定義類名。如果我想使用條件語(yǔ)句來定義是否應(yīng)將類應(yīng)用于我的元素,我可以使用以下代碼:

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

根據(jù)布爾狀態(tài),我的標(biāo)記將是:

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

對(duì)于 true 條件,或:

<div>
  Warning!
</div>

對(duì)于 false 條件。請(qǐng)注意,當(dāng)我為該類指定 isUrgent 時(shí),Ember 對(duì)該名稱進(jìn)行了 dasher 處理,并將該類呈現(xiàn)為 is-urgent。如果您希望根據(jù)結(jié)果指定自己的類,可以使用類似于三元語(yǔ)句的條件表達(dá)式:

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

這將根據(jù) isUrgent 的條件值返回該類的 urgentnormal


了解模板

模板將成為用戶界面的基礎(chǔ),因此花時(shí)間閱讀 Ember 和 Handlebars 站點(diǎn)上的文檔以充分了解它們的整體功能非常重要。即使您不使用 Ember,Handlebars 也是一個(gè)適合您日常使用的出色框架,并且值得投資學(xué)習(xí)如何使用它。

Gabriel Manricks 在 Nettuts+ 上編寫了一篇關(guān)于 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1488
72
How to diagnose high CPU usage caused by WordPress How to diagnose high CPU usage caused by WordPress Jul 06, 2025 am 12:08 AM

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

How to minify JavaScript files in WordPress How to minify JavaScript files in WordPress Jul 07, 2025 am 01:11 AM

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

How to prevent comment spam programmatically How to prevent comment spam programmatically Jul 08, 2025 am 12:04 AM

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

How to enqueue assets for a Gutenberg block How to enqueue assets for a Gutenberg block Jul 09, 2025 am 12:14 AM

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

How to add custom fields to users How to add custom fields to users Jul 06, 2025 am 12:18 AM

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

How to add custom rewrite rules How to add custom rewrite rules Jul 08, 2025 am 12:11 AM

The key to adding custom rewrite rules in WordPress is to use the add_rewrite_rule function and make sure the rules take effect correctly. 1. Use add_rewrite_rule to register the rule, the format is add_rewrite_rule($regex,$redirect,$after), where $regex is a regular expression matching URL, $redirect specifies the actual query, and $after controls the rule location; 2. Custom query variables need to be added through add_filter; 3. After modification, the fixed link settings must be refreshed; 4. It is recommended to place the rule in 'top' to avoid conflicts; 5. You can use the plug-in to view the current rule for convenience

How to optimize WordPress robots txt How to optimize WordPress robots txt Jul 13, 2025 am 12:37 AM

robots.txt is crucial to the SEO of WordPress websites, and can guide search engines to crawl behavior, avoid duplicate content and improve efficiency. 1. Block system paths such as /wp-admin/ and /wp-includes/, but avoid accidentally blocking the /uploads/ directory; 2. Add Sitemap paths such as Sitemap: https://yourdomain.com/sitemap.xml to help search engines quickly discover site maps; 3. Limit /page/ and URLs with parameters to reduce crawler waste, but be careful not to block important archive pages; 4. Avoid common mistakes such as accidentally blocking the entire site, cache plug-in affecting updates, and ignoring the matching of mobile terminals and subdomains.

How to profile WordPress performance How to profile WordPress performance Jul 07, 2025 am 12:43 AM

1. Use performance analysis plug-in to quickly locate problems. For example, QueryMonitor can view the number of database queries and PHP errors, BlackboxProfiler generates function execution reports, and NewRelic provides server-level analysis; 2. Analyzing PHP execution performance requires checking time-consuming functions, debugging tools usage and memory allocation, such as Xdebug generates flame graphs to assist in optimization; 3. Monitor database query efficiency can be checked through slow query logs and index checks, QueryMonitor can list all SQL and sort by time; 4. Combining external tools such as GooglePageSpeedInsights, GTmetrix and WebPageTest to evaluate front-end plus

See all articles