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
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With