4

Is it possible to output only the first word of the title of an entry in a template? If so, how? Thanks!

10

Yes, you can do this with Twig alone. Here's how:

{{ entry.title|split(' ')|slice(0, 1)|join }}

This series of Twig filters:

  1. Uses split to turn the title into an array, splitting on spaces.
  2. Passes that array through slice to grab the first item in the array.
  3. Then uses join to turn the array back into a string for output. The array is now just one item (the first word of the title), but join is needed because Twig doesn't want to treat an array as a string.
4

There is also a nice plugin called Hacksaw that gives you a handful of helpers. With this you can do {{ entry.title|hack(words='1') }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.