34
votes
Accepted
How can I add a dynamic "active" CSS class to the navigation on any given page?
Tip: To keep it short and reusable I would recommend that you wrap your preferred "check-method" in a Twig macro, I like Anna's version the most:
_macros.html:
{% macro is_active(segment) %}{% if ...
32
votes
How can I add a dynamic "active" CSS class to the navigation on any given page?
Assuming you use a structure called pages to create your navigation and the entry variable represents the currently viewed entry, you can output your navigation and active state as follows:
<ul&...
20
votes
Accepted
How does the negative (not) conditional work in Twig?
Twig != is a comparison operator.
The following comparison operators are supported in any expression: ==, !=, <, >, >=, and <=
You can use != to compare any two things that php lets you ...
18
votes
Remove the last comma in an inline list of tags?
There's a couple of special variables available while for looping through an array. In your case I'd make use of loop.last.
{{ tag }}{{ not loop.last ? ', ' }}
This is the expression using the ...
15
votes
How can I add a dynamic "active" CSS class to the navigation on any given page?
craft.request is useful for setting an "active" class based on URL segments.
If your URL was: domain.com/sale/products/shirts
You could write conditionals like the following to target each segment:
...
15
votes
Accepted
How Can I Include a Conditional for First Type of Matrix
You could first set a variable to test against and then change it the first time the block type appears.
{% set firstTime = true %}
{% for block in entry.matrixField %}
{% if block.type == "...
14
votes
Accepted
A/B testing - how to in Craft?
You can set a cookie from your template, which assigns visitors to specific groups:
Craft 2: (Use the LJ Cookies plugin)
{% set testGroup = craft.lj_cookies.get('group') %}
{% if not testGroup %}
...
13
votes
How can I add a dynamic "active" CSS class to the navigation on any given page?
Barrel Strength also have a URL segment based plugin called Sprout Active, with docs/examples here.
13
votes
Accepted
How do I use divisibleby() in a for loop to display two columns?
Instead of using the divisibleby-function you can use the batch-filter:
{% for row in entriesInYear|batch(2) %}
<div class="row">
{% for entry in row %}
<div class="block_txt">...
12
votes
Accepted
Avoid notice of variable's not being set within dev mode
I've had luck using "is defined" before using other logic operators.
This should do it:
{% if entry.title is defined and entry.title | length == 0 %}
{% set entry = craft.entries.section('...
12
votes
How can I add a dynamic "active" CSS class to the navigation on any given page?
Here's yet another way you can do it (in some circumstances) and it's nice and DRY:
Craft 2
{% if craft.request.getPath() == entry.uri %}
Craft 3
{% if craft.app.request.pathInfo == entry.uri %}
12
votes
From a template, how can you order entries by one field, and if that field is empty a different field?
There are several ways you could attack this, but probably the easiest is directly from the SQL side with something like this using a SQL CASE statement:
{% set entries = craft.entries.section('news')...
11
votes
Accepted
Is Shorter Twig Conditional possible?
The Containment Operator helps with this...
It returns true if the left operand is contained in the right
{% if craft.request.getSegment(2) in ['knowledge', 'search'] %}
OR
{% if craft.request....
11
votes
How can I add a dynamic "active" CSS class to the navigation on any given page?
In your template you can set a var in twig:
{% set active = 'blog' %}
And then in your navigation you can run an if statement to see what the var is
<nav>
<a {% if active = 'homepage' %...
11
votes
Accepted
Comparison "or" conditional
You want:
{% if craft.request.firstSegment == 'This' or craft.request.firstSegment == 'That' %}
or this would work:
{% if craft.request.firstSegment in ['This', 'That'] %}
11
votes
Accepted
Select entries starting with same letter from alphabet list
First, you should create a dynamic route (something like "games/glossary/<slug>") and point it to a template. A dynamic route means you won't have to create a template for every letter. Note the ...
10
votes
How do I use divisibleby() in a for loop to display two columns?
If you wish to use divisibleby to solve this problem, the key is in how you use the loop.index and loop.index0 variables.
loop.index counts the iterations in your loop starting with the number 1
loop....
10
votes
Accepted
Remove the last comma in an inline list of tags?
An alternative, if you are getting the tags from the Tag Field type, is the Join filter:
{% if post.tags | length %}
Tags: {{ post.tags | join(', ') }}
{% endif %}
10
votes
Accepted
Conditionally Display Content if Section
You're close!
SectionModel has 'name' and 'handle' attributes and one of those is probably what you're looking for.
{% if entry.section.handle == 'lettings' %}
{{ entry.rentFrequency.label }}
{% ...
9
votes
How to get IP address without a plugin?
From PHP:
if (craft()->request->getIpAddress() == '255.255.255.255')
{
...
}
Note from the docs that this is a "best guess" and can easily be spoofed, so you shouldn't use it to hide any ...
9
votes
Conditional Parsing Issues
This looks like a situation where you might get away with just using Twig's default filter:
{{ entry.metaTitle|default(title|default(siteName)) }}
It works even with undefined or empty strings, and ...
9
votes
Show content if logged in user is in userGroup1 OR userGroup2?
According to the docs, the userModel.isInGroup() method takes a "user group model, its handle, or ID" – in other words, it can only test for membership in a single group, not several.
What you want ...
8
votes
Accepted
Identify immediate siblings block type in matrix
Fun question! :)
You can use getNext() and getPrev() Methods on the MatrixBlockModel documentation page.
{% for point in entry.keyPoints %}
{# if this is the "typeToWrap" block type #}
{% ...
8
votes
Accepted
Using an IF-statement to define the Entry URL Format
Alright, I was able to figure it out myself:
channel{% if object.type == 'xyz' %}/{type}{% endif %}/{slug}
produces the desired results. The section for Dynamic Entry Titles in the docs pointed me ...
8
votes
Accepted
How to get IP address without a plugin?
To make use of your visitors IP address, use {{ craft.request.getIpAddress() }} in Craft 2.5. In Craft 3.x, there is {{ craft.app.request.userIP }}.
8
votes
Correct code for a conditional field?
It depends. Technically to determine if a variable is not empty (keep in mind '0' or 'false' are not considered empty), you can use Twig's 'is not empty':
{% if entry.myField is not empty %}...{% ...
8
votes
Accepted
When to use "if" or "without"?
For your example, you should exclude the fictional towns in the initial query itself rather than filtering them out afterwards:
{% set towns = craft.entries.section('towns').townFictional('not 1')....
7
votes
How can I add a dynamic "active" CSS class to the navigation on any given page?
Another way to achieve this:
{% for entry in entries %}
{% set active = craft.request.path ~ '/' matches "|^#{entry.uri}/|" %}
<a href="{{ entry.url }}" class="{{ active ? 'is-...
7
votes
Accepted
How to use a global variable in a conditional statement if an entries relation field is empty?
The reason it wasn't rendering is because my original entry field is an Entries Field (see templating examples in the docs). The relationship fieldtypes (Entries, Assets, Users) require that you ...
7
votes
Identify immediate siblings block type in matrix
You can do that by using the next parameter...
{% for block in entry.myMatrixField %}
{% if block.next %}
<p>Next block type is: {{ block.next.type }}</p>
{% endif %}
{% ...
Only top scored, non community-wiki answers of a minimum length are eligible
Related Tags
conditional × 129templating × 34
matrix × 15
forloop × 9
field × 8
entries × 7
categories × 7
url × 7
entry × 6
logic × 6
navigation × 5
variable × 5
datetime × 4
entries-field × 4
assets × 3
plugin-craftcommerce × 3
form × 3
structure × 3
sections × 3
category × 3
entry-type × 3
limit × 3
craft3 × 2
plugin-development × 2
localization × 2