Contents
How to check if a variable is null in twig?
So the shortest and safest way (I know) to check whether a variable is empty (null, false, empty string/array, etc): I don’t think you can. This is because if a variable is undefined (not set) in the twig template, it looks like NULL or none (in twig terms). I’m pretty sure this is to suppress bad access errors from occurring in the template.
Why is Symfony-Twig defined and is not null?
This does not work because a variable which is null in twig is defnied, but if you check for null first and it is not defined it will throw an error. This will work because we check if it is defined first and will abord when not. Only if the variable is defined we check if it is null.
How to check if a string variable is null?
{% if foo|trim %} seems to be enough (assuming that foo is the variable to check). If foo is not null, trim removes whitespaces. Also, if handles empty string or null as false, and true otherwise, so no more is required.
How to check for empty fields in twig templates?
Using “|render”, “|strip_tags” is only good if you have your output properly cached, and it still might not cover all edge cases. From what I can see here – it’s a entity template. In this case you can get values directly from entity (which in most cases available in template).
How to check if a variable exists and it’s not empty?
Content verification of variables in Twig can be pretty hard without the dump extension. Even with it, sometimes you will be lazy and you will assume the content of some variables sent from PHP to Twig, as usual a variable can be empty and according to it, you may want to do something different like printing other text etc.
Is there Drupal specific documentation for Twig?
“Drupal specific documentation for twig” – link, you are welcome. Drupal already expands twig a lot, so you cannot avoid learning “drupal specific” twig. “Newcomer has maybe no hope without a holding hand” – we all sitting here to help newcomers to do stuff in best, the most efficient way possible.