lzb/handlebars/object
Registers a Handlebars helper of your own, which is the only way to call a PHP function from a block's Handlebars template.
It fires at the end of LazyBlocks_Handlebars::prepare(), on the WordPress init action, after the built-in helpers are in place. Registering a helper under a name that already exists replaces it, so this is also where truncate, compare, math, date_i18n, do_shortcode and wp_get_attachment_image can be swapped for versions of your own.
Attributes
| Name | Type | Description |
|---|---|---|
$handlebars | Object | Handlebars\Handlebars engine used to render every block |
Usage
function my_lzb_handlebars_object( $handlebars ) {
// {{price 1499 'EUR'}} renders as "€14.99".
$handlebars->registerHelper(
'price',
function ( $cents, $currency = 'USD' ) {
$symbols = array( 'USD' => '$', 'EUR' => '€', 'GBP' => '£' );
$symbol = isset( $symbols[ $currency ] ) ? $symbols[ $currency ] : '';
return new \Handlebars\SafeString(
$symbol . number_format_i18n( (int) $cents / 100, 2 )
);
}
);
}
add_action( 'lzb/handlebars/object', 'my_lzb_handlebars_object' );Wrap markup in \Handlebars\SafeString, as above. A helper's return value is escaped unless it is a SafeString, so a helper returning <strong> prints the tags as text. Return a plain string for anything that should be escaped, which is everything the user typed.
Arguments arrive as strings from the template, so cast before doing arithmetic. A helper called with fewer arguments than it declares can receive the Handlebars options array in place of the missing one rather than nothing at all, which is why the built-in helpers inspect their optional arguments before using them.
The helpers Lazy Blocks ships with are listed in Handlebars.