Skip to content

Instantly share code, notes, and snippets.

@KatieMFritz
Last active October 5, 2022 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KatieMFritz/7ee0a2c3cdc1a51d94c960f483cddea9 to your computer and use it in GitHub Desktop.
Save KatieMFritz/7ee0a2c3cdc1a51d94c960f483cddea9 to your computer and use it in GitHub Desktop.
Twig Single File Component

Single File Component template for Twig

This is heavily influenced by the Vue 2 single file component standards explained in the Vue 2 style guide.

Principles

  • Separate content/API/logic from presentation markup
  • Support using a component library
  • Make it easier to read Twig components, especially seeing dependencies and variables
  • Reduce friction for devs switching between Vue and Twig
  • Make it easier to nest components
  • Encourage inline documentation

Implementation

Use a text expansion tool or something like Hygen to create the new template.

{# ℹ️ Component name
==================================================================================================
Component description
Where to find it on the site
Links to references or documentation
#}
{# 🔌 EXTENDS #}
If you're extending another template, put that function here.
{# 🧩 INCLUDES AND IMPORTS #}
Import your macros here, so you can see at a glance which are used.
Also list any other components that you include or embed later (comment them out).
{# 🎁 PROPS #}
Set all your variables that get directly passed from the parent template or entry.
Err on the side of being very explicit! This makes it easier to see what data is needed when you include
this template from another one.
{# 📀 DATA #}
Any static variables that you've extracted for convenience
{# 🤖 COMPUTED #}
Dynamic variables that modify props
{# 🦾 METHODS #}
Any component-specific macros, Sprig functions, or other methods or functions that need to come after everything else
{# ✨ TEMPLATE ✨ #}
{# ================================================================================================= #}
The markup goes here. There should be as little Twig logic as possible here.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment