Skip to main content
13 votes
Accepted

Overwrite value in object in array

Solution This won't work in Twig as presented in the question (see why below). Instead, users would need to be changed to an associative array (or "hash" in Twig terminology) with keys that aren't ...
Ryan's user avatar
  • 1,952
10 votes
Accepted

Alphabetical index for a list of entries

First, sort all entries by multiple criteria: {# get our entries and order by firstname, lastname #} {% set allEntries = craft.entries.section('entries').orderBy('lastname asc, firstname asc').all() %...
Urs's user avatar
  • 639
9 votes

Is there a way to check if a value exists in an array in twig?

Like you said, to test if a value exists in a Twig array you'd do: {% if myValue in ['apples', 'oranges'] %} {# do something... #} {% endif %} To check whether the value is an array or object ...
Jamie Pittock's user avatar
6 votes
Accepted

Conditional to detect mobile devices with getUserAgent?

Unlike in PHP, it's not actually possible to break a for loop in Twig. To work around that fact, you can use the for loop to set a flag, and then put the conditional outside the loop: {% set ...
Mats Mikkel Rummelhoff's user avatar
6 votes
Accepted

Impossible to invoke a method ("limit") on an array... but it's not an array?

I'm not calling .all(), so this is still an object, right? Nope. When you execute the for loop, it will explicitly run the database query and return the array of results. You're probably getting a ...
Brad Bell's user avatar
  • 67.5k
5 votes

Overwrite value in object in array

This could also be accomplished with the map filter, if you’re running Craft 3.1.29 or later: {% set users = [ {name: 'Bill', age: 25}, {name: 'Tim', age: 30}, {name: 'John', age: 32} ] %} ...
Brandon Kelly's user avatar
5 votes
Accepted

Pagination and Entry Model on Homepage

project.images is an array because you are eager-loading the images. Since you’re only loading one project entry, you’re not actually gaining anything by eager-loading the images (or category), ...
Brandon Kelly's user avatar
4 votes
Accepted

Random Number from range

Building off of Brad's answer, you might consider using a for loop to render your markup, instead of setting all of those variables: {% set range = range(10, 90) %} {% set totalDivs = 5 %} <div ...
Mats Mikkel Rummelhoff's user avatar
4 votes

Returning an array to Twig from a plugin

Your plugin should be able to handle PHP arrays just fine. craft/plugins/myplugin/variables/MyPluginVariable.php function getArray() { return array('hi', 'there'); } craft/templates/template....
Fuglsetrampen's user avatar
4 votes
Accepted

How can I iterate through an array of field handles for an entry?

I figured it out! I ditched the macro and just included the following in my template: {% for field in courseFields %} <section class="col-xl mb-3"> <h2 id="{{ field.handle }}">{{ ...
Katie Fritz's user avatar
4 votes
Accepted

Updating Array Variable In Extending Template

You can only access the parent's variable, not modify it. You could however simply add another block specifically for the body class, like so: Layout template: <body class="{% block body_class %}...
Udo's user avatar
  • 607
4 votes

How can I tell if a variable is an array or an entry/element query?

you can use the instance of twig test here. You want to flip your logic, so test for Query object first else array stuff but this should work I think. To get the specific class just {% dd props....
billythekid's user avatar
4 votes

Checking if a value is in an array of IDS - using a filter?

You could use filter to get only the variant that matches the wheelSpacer variable. This will return an array, so you can use first to get the first matching variant (since presumably product.variants ...
MoritzLost's user avatar
  • 11.3k
3 votes
Accepted

Iterate through all entries and count a specific value

Before we proceed, let me say that whilst the following will work, I personally think this is a poor use of Twig. It's far better to collate this information in a simple plugin, rather than jumping ...
Stephen Lewis's user avatar
3 votes
Accepted

Call a Craft variable inside array

To output variables inside an array like that you'd simply omit the twig braces.. at the moment the ' are telling whatever is inside them to output as a string. UPDATE: try adding parentheses around ...
Luke Pearce's user avatar
  • 3,863
3 votes
Accepted

Adding a random entry to an array

You can use slice and merge filters to “insert” that random entry into your array of entries. In the following example I’m using the id param to query for the selected entries and I’m also setting ...
carlcs's user avatar
  • 36.2k
3 votes

Can I exclude a commerce address by ID when retrieving a list of addresses?

I still haven't found a succinct way to exclude a particular address by ID within the commerce customer addresses tags, but I did come up with the following as a way to get a nice clean set of ...
jthomas's user avatar
  • 373
3 votes
Accepted

Possible to merge and sum the values of an array?

What you need to do is to add the row.points to any existing points for each type, before merging – otherwise you'll just overwrite the existing type/attribute and its values (in other words, the |...
Mats Mikkel Rummelhoff's user avatar
3 votes
Accepted

Eager-load and pagination

with is just another query param, like limit or whatever parameters you’re defining in entryParams. The {% paginate %} tag requires that you pass in an ElementCriteriaModel, but as soon as you call ...
Brandon Kelly's user avatar
3 votes

Create an object of objects with merge

You're overriding the "title" and "link" properties on every iteration. Wrap the itemObject object in [] to merge the whole object into your array. {% set object = object|merge([itemObject]) %}
carlcs's user avatar
  • 36.2k
3 votes
Accepted

Empty .getParam() does not return an array with dump()

The behaviour you're seeing is by design – craft.request.getQuery() will return all GET variables if it's called without arguments, whereas craft.request.getParam() requires the name argument – i.e. ...
Mats Mikkel Rummelhoff's user avatar
3 votes
Accepted

Query two sections filtered by different custom fields, then order them

There's this super useful SuperSort plugin that would make this possible. {% set sortAsTemplate = '{{ object.section == "Exhibitions" ? object.startDate|date("U") : object.date|date("U") }}' %} {% ...
carlcs's user avatar
  • 36.2k
3 votes
Accepted

Check for number less than x in array

Twig isn't very well equipped to deal with more than basic logic and comparisons, but you can accomplish some of these tests with a bit of extra juggling: {% set constraintMet = false %} {% for ...
August Miller's user avatar
3 votes
Accepted

Help with an Entries field to an array I can use elsewhere

At the same time as you are iterating over your Hero posts, you could populate an array that you could then use in your most popular query. This is just sudo code but hopefully you get the idea: {# ...
Oli's user avatar
  • 7,495
3 votes
Accepted

Checking if a value is in an array of IDS - using a filter?

Using the |map filter would work nicely here: {% set variantIds = product.variants|map(variant => variant.id) %} {% if wheelSpacer in variantIds %} ... {% endif %}
Mats Mikkel Rummelhoff's user avatar
3 votes

Merging classes in Twig based on component and context

You can solve this using the merge filter. When merging hashes (i.e. associative arrays), properties from the merged hash override properties with the same key in the target hash. Since you're ...
MoritzLost's user avatar
  • 11.3k
3 votes
Accepted

Prevent merge from removing data

As noted in the comments, the problem came from the merge filter being placed outside the for-loop. However, the deeper problem is the procedural code causing a lot of noise, making it difficult to ...
MoritzLost's user avatar
  • 11.3k
3 votes

How do I only display a list of users that have entries and hide the rest

I would try it this way: {% set authors = craft.entries.section('agenda').datumBeginn('>= ' ~ todayMidnight).select(['author']).all() %} Authors should be a list of user ids. Credit to an older ...
cherrykoda's user avatar
  • 1,059
2 votes

What is the best way to exclude an array of entries?

For Craft 3, after you get the ids you don't want (that would be an array), create your query to disregard those ids in the following way: {# omitIds = array of ids you want ommited #} {% set ...
grom's user avatar
  • 46
2 votes

Random Number from range

Instead of using shuffle, which is only available in the extra Array extensions library, you could just use random. {% set range = range(10, 90) %} {% set randomHeight1 = random(range) %} {% set ...
Brad Bell's user avatar
  • 67.5k

Only top scored, non community-wiki answers of a minimum length are eligible