I have a const array that I need to access in twig, here is my constants class:
class Constants{
public const NOTIFICATIONS_LIKE_POST = 0;
public const NOTIFICATIONS_COMMENT_POST = 1;
public const NOTIFICATIONS_REPLY_COMMENT = 2;
public const NOTIFICATIONS_POSTED_NEW_POST = 3;
public const NOTIFICATIONS_POSTED_NEW_PHOTO = 4;
public const NOTIFICATIONS_POSTED_NEW_VIDEO = 5;
public const NOTIFICATIONS_POSTED_NEW_GALLERY = 6;
public NOTIFICATIONS_ARRAY= array(
self::NOTIFICATIONS_LIKE_POST => " liked your ",
self::NOTIFICATIONS_COMMENT_POST => " commented on your ",
self::NOTIFICATIONS_REPLY_COMMENT => " replied to your ",
self::NOTIFICATIONS_POSTED_NEW_POST => " posted a new ",
self::NOTIFICATIONS_POSTED_NEW_PHOTO => " posted a new ",
self::NOTIFICATIONS_POSTED_NEW_VIDEO => " posted a new ",
self::NOTIFICATIONS_POSTED_NEW_GALLERY => "posted a new "
);
}
Here's what it looks like when I want to add it in my twig:
{% for notification in notifications %}
<div class="notice" onclick="window.open('single-post.html');">
<div class="header">
<img src="{{ getAvatar(notification.fromUser) }}" width="128" class="avatar">
<div class="content">
<a href="../profile.html" class="user">{{ notification.fromUser.username }}</a>
<!-- so specifically the following line -->
{{ dump(constant("App\\Constants::NOTIFICATIONS_ARRAY[" ~ notification.activity ~ "]")) }}
<div class="footer">
notification.time
</div>
</div>
</div>
</div>
{% endfor %}
Just to show you that twig can "see" this array, here is the output of:
{{ dump(constant("App\\Constants::NOTIFICATIONS_ARRAY")) }}
However when I try to access this array with an index (here is what the code looks like:)
<!-- In this case notification.activity is 2 -->
{{ dump(constant("App\\Constants::NOTIFICATIONS_ARRAY[" ~ notification.activity ~ "]")) }}
I get the following error:
An exception has been thrown during the rendering of a template ("Warning: constant(): Couldn't find constant App\Constants::NOTIFICATIONS_ARRAY[2]").
Maybe it's just a PHP syntax thing? I don't know why I can't access a specific element of my const array.
The array index isn't part of the name of the constant. The constant is an array:
{{ dump(constant("App\\Constants::NOTIFICATIONS_ARRAY")[notification.activity]) }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With