-
-
Notifications
You must be signed in to change notification settings - Fork 4
Injection
When using the DocumentBinder
, it's preferred to use data-bind
attributes to bind element properties, as explained in the binding section. This is so the HTML source can be used to represent the default, unbound state.
However, sometimes it's useful to only bind a subset of an element's property. This can be done using curly brace injection: two opening curly braces, followed by the name of the bind key, followed by two closing curly braces, {{like_this}}
.
As an example, a link's href
attribute might only need a part of it injecting: <a href="/profile/user/{{username}}">View {{username}}'s profile</a>
. Now, binding the document as usual will inject the username
bind key wherever {{username}}
appears in the bind context.
Here, we bind a list of countries and display their flags by injecting the image's src
and alt
attributes.
Source HTML:
<h1>Wealthiest countries of the world</h1>
<ul>
<li data-list>
<img src="/flags/{{code}}.png" alt="Flag of {{name}}" />
<p data-bind:text="name">Country name</p>
</li>
</ul>
PHP:
function example(DocumentBinder $binder):void {
$countryData = [
["code" => "US", "name" => "United States of America"],
["code" => "CN", "name" => "China"],
["code" => "JP", "name" => "Japan"],
["code" => "DE", "name" => "Germany"],
];
$binder->bindList($countryData);
}
Output HTML:
<h1>Wealthiest countries of the world</h1>
<ul>
<li>
<img src="/flags/US.png" alt="Flag of United States of America" />
<p>United States of America</p>
</li>
<li>
<img src="/flags/CN.png" alt="Flag of China" />
<p>China</p>
</li>
<li>
<img src="/flags/JP.png" alt="Flag of Japan" />
<p>Japan</p>
</li>
<li>
<img src="/flags/DE.png" alt="Flag of Germany" />
<p>Germany</p>
</li>
</ul>
Next, learn how to bind lists of data with data-list
attributes.
PHP.Gt/DomTemplate is a separately maintained component of PHP.Gt/WebEngine.
- Bind data to HTML elements with
data-bind
attributes - Bind key modifiers
- Inject data into HTML with
{{curly braces}}
- Bind lists of data with
data-list
attributes - Bind nested lists with
data-bind:list
- Automatically remove unbound elements
- Bind tabular data into HTML tables
- Using objects to represent bindable data