1

This might be impossible, but can you lookup a value in a key-value array with the value in a craft entry field? And perform math with it in twig? I'm trying to simplify my template code.

I have a key value array like so

{%
set aspectRatioSetting = {
    'four_three' : '0.75',
    'three_two' : '0.666666666667',
    'sixteen_nine' : '0.5625',
    'one_one' : '1'
} %}

And I'd like to be able to use those values in a math operation, the specific value looked up by a value in a custom entry field.

{% set transformParams = { width: 1250, height: 1250 * aspectRatioSetting.four_three } %}

where the value of the "four_three" key in the array is used in the math operation. Only the specific key would be set by the value in an entry field.

{% set transformParams = { width: 1250, height: 1250 * aspectRatioSetting.(entry.aspectRatio) } %}

There's not a good way for me to type it up because this clearly doesn't work. I'm just wondering if it's somehow possible.

Or maybe I'm just overcomplicating things in an attempt to simplify things : /

3

Two options here ...

{% set transformParams = { width: 1250, height: 1250 * aspectRatioSetting[entry.aspectRatio] } %}

Or just give the select field a value that represents the number, not the word. So set a value of 0.75 instead of four_three, and let the label be Four/Three (or whatever seems fit).

| improve this answer | |
  • You have a great point about the select field value. I was using the value as a class-name in that I could style with CSS (since CSS has issues with numbers as class names). But I suppose I can just use the label for that and keep the value numeric as you say. – Dave Joyce Oct 26 '15 at 20:04
  • However, going back to the original idea of using the key-value array, I tried what you suggested and I got a PHP warning: "array_key_exists(): The first argument should be either a string or an integer" – Dave Joyce Oct 26 '15 at 20:04
  • 2
    What if you use entry.aspectRatio.value ? – Paul Oct 26 '15 at 20:24
  • yup! That did the trick! Thanks :) Although I ended up going with your other suggestion, I now have a future trick in my book. – Dave Joyce Oct 27 '15 at 14:31
1

Try:

{% set transformParams = { width: 1250, height: 1250 * (aspectRatioSetting.four_three|trim) } %}

| improve this answer | |
  • That's not exactly what I was looking to do originally, but adding trim helped for Paul's suggested solution of using number values in the dropdown field. So thanks! – Dave Joyce Oct 26 '15 at 20:27
  • It's hackish, but ensures the types are the same. More of a twig bug IMO. – Steve Adams Oct 26 '15 at 20:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.