2

Is there a way—using Twig—to check if a variable is set based on a string of the same name?

In this example below, editLink.object is a string with the value of "entryAlias". I want to check to see if a variable, entryAlias, has been set and to see if it's an entry.

{% if "#{editLink.object}" is same as(editLink.object) %}
    it workes
{% else %}
    not so much
{% endif %}

I've looked into same as and is, but I think the problem I'm having is converting the string to an object. Also, I'm pretty sure this can just be done using PHP, but I'd like to see if it can be done within Craft's Twig so this can be cached as part of a template.

2

I don't think same as is what you're looking for in this case. Try the Twig attribute function instead...

If you're dealing with the global scope, it would be something like this:

{{ attribute(_context, 'myVariable') is defined ? 'Variable exists' : 'Variable does not exist' }}

You can always use _context to reference your current scope.

If you're testing to see if an object/array contains a property, it's practically identical:

{{ attribute(myObject, 'myProperty') is defined ? 'Property exists' : 'Property does not exist' }}

Building off of that...

  • attribute(x, y) is defined will return a boolean, whether or not it exists.
  • {% set value = attribute(x, y) %} will return the value (assuming it exists).
3

After a Slack conversation with @carlcs, we discovered another slick solution...

{{ 'myVariable' in _context|keys }}
  • The in operator works much like PHP's in_array function.
  • The keys filter works just like PHP's array_keys function.

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.