Skip to content

Injection

Greg Bowler edited this page Feb 27, 2023 · 6 revisions

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.

Injection examples

Image sources

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.