Docs
Variables

Variables

Make backend-generated variables available to frontend AlpineJS code.

Zermatt variables (key => value) are chunks of data generated by the backend (PHP) and made available to the frontend.

  1. The backend sets a variable.
  2. The Zermatt.Variables JS object is populated with the variable.
  3. AlpineJS code in templates and Zermatt modules have access to Zermatt.Variables.

Declaring a variable in a PHP file

public function someMethod() {
    zermatt_variable('customer', ['name' => 'John Doe', 'age' => 46])
}

Declaring a variable in a template

<?php
    zermatt_variable('customer', $block->getCustomer())
?>

Using the variable in AlpineJS context

{
  name: Zermatt.Variables.customer.name
  age: Zermatt.Variables.customer.age
  greet() {
    return `Hello, ${this.name}, aged ${this.age}!`
  }
}

Immutability

As variables come from the backend to the frontend, you should not mutate a variable in the JS code.

So, please avoid doing: Zermatt.Variables.customer.name = 'Bad Idea'.

Accepted variable values

  • Literals (string, int, float, arrays)
  • Magento objects inheriting \Magento\Framework\DataObject
  • Magento collections inheriting \Magento\Framework\Data\Collection
  • Magento API objects inheriting \Magento\Framework\Api\AbstractSimpleObject