Set a new value depending on what the original value is? - drupal

In Drupal views, I have a twig variable available to me called {{ name }}. This stores a list of taxonomy terms depending on the type of content used. I currently have a function running something like this that works:
{% if name == "Tax1" %}
Download
{% elseif name == "Tax2" %}
Download
{% endif %}
However, I feel like there is a better way for me to go about doing this. As an example isn't something like this supposed to work?
{%
set newval = [
name == "Tax1" ? 'file1.pdf' : 'file2.pdf'
]
%}
Download
Pretty much what I'm trying to state above is, if the value of name is equal to "Tax1", print out file1.pdf, else print file2.pdf.
I have very basic twig knowledge and I haven't touched it in a couple years so if anyone could help me out with this, that would be great.

Thanks to #DarkBee for the help. I must have been overthinking as the answer was fairly simple.
The below solution worked for what I was initially asking:
Download
However, I ended up needing a third default option if not the first two so the below code is what I ended up using:
{% if name == "Tax1" or name == "Tax2" %}
Download
{% else %}
<span class="stat">Other Option</span>
{% endif %}

Related

pluralize results if plural in symfony (good practice)

I have a filter bar that let me search some results within my database.
I have a flash message that shows how many results are found when I enter a word inside it.
this is my controller
if ($filter != '') {
$this->get('session')->getFlashBag()->add('info', 'worked!');
}
and this is in my template
{% for message in app.session.flashbag.get('info') %}
{{ message }}
{% endfor %}
so when i research things actually, whether I have 1 result or more it doesn't change my sentence.
résultats is still written with an s as it is hard coded. How can I create something that will allow me to pluralize and singularize a word in my template? Should I go directly in the controller for that ?
EDIT
I used this method directly in the template but I don't think it is a "good practice" one. Any help for making that better?
{{ results.getTotalItemCount }}
{% if results.getTotalItemCount <= 1 %}
{{ 'this.is.your.result'|trans({ '%count%': results.getTotalItemCount}) }}
{% else %}
{{ 'this.is.your.results'|trans({ '%count%': results.getTotalItemCount}) }}
{% endif %}
in translation
this:
is:
your.result: "résultat"
your.results: "résultats"
You should maybe check pluralization in translations here, you can use transChoice() method, it is explained here how to use it.
Here you can see how to use it in twig:
https://stackoverflow.com/a/10817495/5258172
Edit:
your answer in question can be done like this:
this:
is:
your.result: "1 résultat|%count% résultats"
and then in your twig:
{{ 'this.is.your.result'|transchoice(results.getTotalItemCount) }}

Symfony/Twig Set variables in if condition

I know this is really trivial and not that important but it could save me some lifetime...
You know you can declare variables in PHP in a if block
if( $row = $sql->fetch ){
//do something with the $row if $row = null this part is skipped
}
In twig I can't do for example (set image = object.image, if my object has no image, the variable image becomes null and the if statement does not become true
{% if image = object.image %}
<img src="{{ image.getUrl() }}"> //and so on
{% endif %}
Instead I have to make it this way (check if the object has an image, if yes save it to new variable and do some stuff with it)
{% if object.image %}
{% set image = object.image %}
<img src="{{ image.getUrl() }}"> //and so on
{% endif %}
Of course I know this is no first world problem and you may think my question is useless but I have to write those "longer" statements many times a day so I could be few minutes faster in the end.
So is there a syntax that allows me to set variables in an if block instead of comparing them?
Thank you very much
EDIT
I't the same like this Can I define a variable in a PHP if condition? just in twig
No, there is no way to declare a variable inside an if tag. Variables can only be set using the set tag.
You can set it with a ternary operator.
{% set result = condition ? "a": "b" %}
You can use (check here for more help) :
{% if object.image is defined or object.image is not null %}
<img src="{{ image.url }}">
{% endif %}
Hope this helps !

Rendering a choice field type (symfony2) as buttons

I have a problem which I cannot solve. How shall I approach the following: I have a choice field with 4 different entries, which I am rendering perfectly in a select form (twig). However, I would like to show the 4 entries as 4 separate buttons. How do I change the input type of those 4? Or do I have to do anything totally different?
Thanks for your help
-AS
edit (new following question):
Alexandru, thanks for your help. That was very helpful.
I added in the fields.html.twig the following:
{% block _appbundle_action_Style_widget -%}
{% for child in form %}
<input type="button" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
{% endfor %}
{%- endblock _appbundle_action_Style_widget %}
However, when I render it it tells me that there is an array to string conversion, which somehow does not work. When I delete the widget attributes, value, and checked parts, the buttons are getting rendered without those then.
You have a few options to choose from:
You can create a new field type, let's call it "button_group", that will extend the "choice" type and write the custom Twig for it, something like this:
https://github.com/symfony/symfony/blob/2.7/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_3_layout.html.twig#L95
You can use the "choice" field type with the option: expanded => true. And create a custom form template for it only for the form you need it in:
http://symfony.com/doc/current/cookbook/form/form_customization.html#what-are-form-themes
Ok I solved my problem. In order to access the value variable I have to use the following {{ child.vars.value }}. With this I can now take the variable and put it into the value tag.
Thanks for your help.

Symfony2 - get value displayed to user for choice field in twig

I am trying to display the "label" (ie, value displayed to user) of a choice field in my twig template. I'm using Symfony 2.3. I just need the label associated with the actual current value of the field.
I finally figured out a way to do it that requires looping through every choice option, but am now wondering if there is a more efficient way? Here is my working code:
{% for choice in form.myfield.vars.choices %}
{% if choice.value == form.myfield.vars.value %}
{{ choice.label }}
{% endif %}
{% endfor %}
I'm looking for something like this (non-working code):
{{ form.myfield.vars.choices[form.myfield.vars.value].label }}
Is there a more efficient way, or is my solution the best possible?

twig convert a string to the object that it represent

imaging that i have a object and which can be called in a twig template like this:
{{ object1.object2.object3.property3A }}
well, it will show me the content if we use php to write is :
$object1->getObject2()->getObject3()->getProperty3A();
My question is if i have a string ,
$refString="object1.object2.object3.property3A";
and then it is passed to twig, how could i get the property3A? For my experience, we can do this in php like this:
$refString="object1->getObject2()->getObject3()->getProperty3A()";
echo $$refString;
But i do not know how to make it work in twig.
I didn't tested this, but i think it schould do the trick.
{#
recursively reading attributes from an object
! object1 must be available !
theValue is the value of property3A
#}
{% for key in "object1.object2.object3.property3A"|split('.') %}
{% if not loop.first %}{# skip the 'object1' part #}
{% set theValue = attribute(theValue|default(object1), key) %}
{% endif %}
{% endfor %}
I don't think there is a "shortcut" to do this in twig. If you can't find a simple way to do this, you can write you own extension, that would convert a STRING_TYPE to a VAR_TYPE.
Twig internals might put you on the right track. This is an example of what is feasable with twig extension and might inspire you.
I ran into a similar situation. This answer will only work if the object you need is available to the template and you know the name of it with a string.
In this case, you can access the object using Twig's Global Variable _context:
{% set object1 = _context['object1'] %}
And then access the methods and variables of the object as normal:
{{ object1.object2.object3.property3A }}

Resources