Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you conditionally pass a variable to Twig

Tags:

php

twig

symfony

So I am building a component and want the ability to bind a value to it or leave it blank. Ideally I would like to do this without the if statement maybe with filters or some type of ternary operator. So can I ever use this without explicitly passing a date

{% if date is not defined %}
    <input type='text' name="date" value="" class="form-control date-picker" />
    <input type='hidden' name="timezone" class="timezone" />
{% else %}
    <input type='text' name="{{date.name | default("date")}}" value="{{ date.value | default("")}}" class="form-control date-picker" />
    <input type='hidden' name="timezone" class="timezone" />
{% endif %}

This is the ugly broken code I ended up with after trying multiple things.

I cannot load the component without giving it a value for date

$date = '';
return $this->render('ComponentBundle:Default:datepicker.html.twig',array(
            'date' => $date,
       ));

The error i get when i don't pass date to the view is

Variable "date" does not exist in ComponentBundle:Default:datepicker.html.twig at line 10
like image 731
jackncoke Avatar asked Dec 07 '25 10:12

jackncoke


1 Answers

You cannot conditionally pass a variable but you can set and test some variables inside twig. example :

{% set var_date = date is defined and date is not empty ? date : {'name': 'date', 'value': ''} %}

<input type='text' name="{{ var_date.name }}" value="{{ var_date.value }}" class="form-control date-picker" />
<input type='hidden' name="timezone" class="timezone" />
like image 98
Heah Avatar answered Dec 11 '25 13:12

Heah