How do you check if an object exists in the Twig templating engine in Symfony2? - symfony

I have a multidimensional array where some objects exist and others don't. I keep getting a
Method "code" for object "stdClass" does not exist in...?
The code I am using in my template is:
{% for item in items %}
<p>{% if item.product.code %}{{ item.product.code }}{% endif %}</p>
{% endfor %}
Some products do not have this code and unfortunately this data structure is provided via a feed, so I cannot change it.
When I looked at the Twig documentation I interpreted that if an object or method was not there it would just return null?

Quickly did a lookup, hope this is works for you :p
defined
defined checks if a variable is defined in the current context. This is very useful if you use the strict_variables option:
{# defined works with variable names #}
{% if foo is defined %}
...
{% endif %}
{# and attributes on variables names #}
{% if foo.bar is defined %}
...
{% endif %}

Related

Issues with passing a variable to a macro

I have a menu block that shows 4 links. I'd like to remove the last one if the user has a specific role.
The menu block is created in a specific twig file, and inside a macro, as follows:
{% import _self as menus %}
{#
We call a macro which calls itself to render the full tree.
#see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}
{% set role = user.role %}
{% macro menu_links(items, attributes, menu_level, elements) %}
{% import _self as menus %}
{% if items %}
<span class='arrow-down'></span>
<ul{{ attributes.setAttribute('id', 'edit-profil-nav') }}>
{% for item in items %}
{% set item_classes = [
'col-xs-12',
'col-sm-12',
items|length == 3 ? 'col-md-4' : 'col-md-3',
item.in_active_trail ? 'active' : 'notactive',
] %}
<li{{ item.attributes.addClass(item_classes) }}>
{{ link(item.title, item.url) }}
</li>
{% endfor %}
</ul>
{{ attach_library('cnas/responsive-navigation') }}
{% endif %}
{% endmacro %}
The major issue I have is that I can't interfere with the macro: I'd like to be able to make comparisons with the user variable, but when I dump it while being in the macro, user shows null.
I found a lot of stuff while looking for an answer, but I've seen everything and its opposite, so I'd like to know if I can do that, and how
Thank you a lot!
macro's in twig have their own scope. You will need to pass the variable user as an argument towards the macro in order to access it.
You could also pass the special variable _context to the macro.
This variables holds all the variables you passed towards the template.

Twig - loop default value

I am trying to print array from the cotroller into the twig temlate. I want to print "-" whenever array is NULL. My problem is that in for-loop case it writes nothing, however single row working fine. Is there some simple way how to do it correctly?
this is not working as i expected
{% for key in keywords|default('-') %}
{{ key~', '}}
{% endfor %}
this is working
{{ key |default('-')}}
You can use an {% else %} construct on a for loop to do something else if the array is null:
{% for key in keywords %}
{{ key~', '}}
{% else %}
-
{% endfor %}
See the documentation here.

How to use twig object variable with at-sign # inside

I send from Symfony object which contains at-sign # in variable.
Object name is invoice and with {{ dump(invoice) }} in twig template I see object and parameter with path:
invoice[0].banSpojDod#showAs
But I dont know how to get value of this banSpojDod#showAs because there is at-sign #.
Could you help me someone please?
You could try with The attribute function can be used to access a "dynamic" attribute of a variable:
{{ attribute(invoice[0], 'banSpojDod#showAs') }}
Hope this help
Ok thanks. Problem was that I used it in loop, and some parameters not exists. I needed to add exist conditions. So my final code works:
{% for f in invoice %}
{% if attribute(f,'banSpojDod#showAs') is defined %}
{{ attribute(f,'banSpojDod#showAs') }}
{% endif %}
{% endfor %}

Symfony2 Twig Conditional Template Name

I'm looking for a way to check in my twig template if the name of the template contains a special word. If that is the case I want to proceed with assigning some stuff. Here is a general idea I have in mind.
{% if [sth like app.request.template_name or sth like that] in `product` %}
// Do some stuff
{% endif % }
Can you guys help me with this?
If you're creating separate template files then you'll know the names and can hardcode the values:
template_1.html.twig:
{% set some_var = 1 %}
{% set another_var = 2 %}
template_2.html.twig:
{% set custom_var = 5 %}
Update:
If you want the template name, you can use:
{% if 'product' in _self.getTemplateName() %}
{# Do stuff #}
{% endif %}

Set a Variable with a Twig Macro

I have to set a variable with a macro, that returns a number, so I have this macro:
{% import _self as self %}
{% macro function_size(field) %}
{% import _self as self %}
{# initial Setup #}
{% set field_length = 0 %}
{# Field #}
{% for key, value in field %}
{% if not (key starts with "#") %}
{% set field_length = field_length + 1 %}
{% endif %}
{% endfor %}
{{ field_length }}
{% endmacro %}
The Macro loops through the entries of a field and returns the count of values, that don't start with "#".
So I set a variable with that value:
{% set image_size = self.function_size(content.field_teaser_image) %}
ATTENTION: With this you will set the Variable with Twig Markup. (You can see that when you debug the variable afterwards.)
To get a number/integer as value you have to convert it to a String (that will be interpreted as a number if you calculate with it)
{% set image_size = image_size.__toString %}
With this I set the Variable successfully with a macro.
My Question: Is this a bad practice, are there better ways how to set an Variable?
Thank you!
Two ways to set variables for twig are fine in my opinion.
1. Use theme and other hooks (inside theme or any module) and pass variable from php,
2. create twig extension/filter
Examples:
Filter:
http://leopathu.com/content/create-custom-twig-filter-drupal-8
Extension:
http://symfony.com/doc/current/templating/twig_extension.html

Resources