Twig in Craft Fields

October 2022

Twig in Craft Fields

As with all content management systems, Craft CMS uses a templating system to create front end pages; twig. Twig templates are HTML files that are sprinkled with bits of Twig code. When Twig loads a template, the first thing it will do is separate the raw HTML code from the Twig code. The raw HTML code will be output to the browser without any tampering.

As I was building the work stats part of my site:

Work Stats

I wanted the numbers to update on their own. I thought to myself, "Wouldn't be nice if this could take care of itself?" I mean, all the raw data is already in the site. Could I actually have twig tags pull database information right into an entry field?

My best friend google eventually found an article about twig templating tips and tricks for Craft CMS. I had used many of the tips before but near the bottom was a paragraph about twig's template_from_string() function. It allows you to parse a string of text as twig code. This means you can put twig syntax like variables or functions in Craft CMS fields. Then you just need to parse this content using template_from_string() function:

{{template_from_string(entry.someField)}}

nystudio107 even tweeted about it.

So what are the actual values in my Craft fields?

  • Years of Experience is the current year minus the year of the first project in my portfolio site
    {{ now|date('Y') - craft.entries.section('projects').orderBy('postDate ASC').one().postDate|date('Y') }}
  • Completed Projects is all the project entries in my portfolio site (even the disabled ones)
    {{ craft.entries.section('projects').anyStatus().count() }}
  • Happy Clients is a little more complicated. Sometimes I work directly with the client, sometimes I work with a design agency and through them there are multiple clients. I made up some math to estimate.
  • Hours of Work was a complete guess but it's also math based all the project entries. I wonder if I could do an api request to my time tracking app to get a more accurate number?