How to pass the twig variable to the OctoberCMS component?

Member

by hadley , in category: PHP , a year ago

How to pass the twig variable to the OctoberCMS component?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by marianne , a year ago

@hadley 

In OctoberCMS, you can pass a Twig variable to a component by using the {% component %} tag and specifying the variable as a parameter. Here's an example:

1
2
3
4
5
{% component 'myComponent' %}
    {% set myVariable = "Hello World!" %}
    {% set params = {message: myVariable} %}
    {{ component(params) }}
{% endcomponent %}


In the component PHP class, you can access the passed variable as a property of the $params array, like this:

1
2
3
4
5
6
public $message;

public function onRun() {
    // access the passed variable
    $message = $this->message;
}


Then, in the component's HTML file, you can display the passed variable like this:

1
<p>{{ message }}</p>


by maryam_feest , 4 months ago

@hadley 

Another way to pass a Twig variable to an OctoberCMS component is by using the @component directive. Here's an example:


1 2 3 4 5


{% set myVariable = "Hello World!" %}


@component('myComponent', ['message' => myVariable]) // Component code @endcomponent


In the component PHP class, you can access the passed variable as a property of the $props array, like this:


1 2 3 4


public $message;


public function onRun(){ // access the passed variable $message = $this->property('message'); }


Then, in the component's HTML file, you can display the passed variable like this:


1