Useful Craft CMS Snippets

Posted on September 12, 2017 | Craft CMS

A few helpful Craft CMS snippets for your reference. These are the most used snippets in many of my Craft CMS projects.

Include another file in a template.

e.g. You have a file called _myfile.html within a includes folder. The file extension .html is to be excluded here.

{% include 'includes/_myfile' %}

Get Matrix field information

e.g. You have a Matrix field for Social Media called socialMedia within a Global called contactDetails. Sub Items are called socialUrl, socialTitle and for this example socialFaCode for the font awesome icon.

<ul>
{% set social = contactDetails.socialMedia %}
{% if social | length %}
{% for socialMediaAccount in social %}
    <li><a target="_blank" href="{{socialMediaAccount.socialUrl}}" title="Follow me on {{socialMediaAccount.socialTitle}}" class="fa fonts-icons {{socialMediaAccount.socialFaCode}}"></a></li>
{% endfor %}
{% endif %} 
</ul>

Get Image from Asset field

e.g. You want to add a logo to your website. You have created a Global called brandSettings and two fields for an SVG (logoSvg) and PNG logo (logoPng).

{% for imagesvg in brandSettings.logoSvg %} 
{{ imagesvg.getUrl() }} 
{% endfor %}
Example:
<a href="{{ siteUrl }}">
    <img src="{% for imagesvg in brandSettings.logoSvg %} {{ imagesvg.getUrl() }} {% endfor %}" onerror="this.src='{% for image in brandSettings.logoPng %} {{ image.getUrl() }} {% endfor %}'" alt="" class="logo">
</a>

Get a list of Categories

e.g. You have created a category called categories and you want to list them out on a page

<ul>
    {% for category in craft.categories.group('categories') %}
    <li><a href="{{ category.url }}" class="">{{ category.title }}</a></li>      
    {% endfor %}
</ul>

Get total number of categories

{% set categoryCount = craft.entries.relatedTo(cats).total() %}
Output like this {{categoryCount}}

Get or target the First Entry in a Loop

e.g. Output or style the first entry differently.

{% if loop.first %} Your Entry Data {% endif %}

Get Craft CMS information

Site Name: {{siteName}}
Site URL: {{siteURL}}
Login URL: {{ loginUrl }}
Logout URL: {{ logoutUrl }}
Full list available here: https://craftcms.com/docs/templating/global-variables