1

I'm making a theme for Bolt (CMS) and it uses the Twig engine. The website contains articles so I get an article's field like this {{ article.body }}

Now what I wanted to achieve was get the first letter of the body of the article and make it big and then display the rest of the article's body (without this first character) normally, you sometimes see this in books. I managed to do that and I successfully change the style of the first character.

However, using most functions that Twig offers in the documentation, I most often get a "<" as the first symbol as when typing the body of the article in the administration panel it automatically puts a <p> tag to the start.

Is there a way to overcome this?! I wouldn't want my client to have to delete the <p> tag every time. I thought there would be an easy way to get the body without any html in it or something else suitable for my use case.

The way it currently works beautifully:

<span class="firstcharacter">{{ article.body[:1] }}</span> {{ article.body[1:] }}</p> 

but this relies on the article not starting with any html

iBobb
  • 1,140
  • 1
  • 14
  • 35

3 Answers3

0

There is a css pseudo-selector for first letter:

.firstcharacter::first-letter{font-size: 50px;}

Would this work for you?

  • I'm actually having a different problem. The design part is okay so my question is about Twig. I change the style of the first character successfully, the problem is the first character could be an html < character because twig returns it like that. – iBobb Oct 29 '16 at 00:50
  • Ah ok - in that case I cannot help as I'm not familiar with either twig nor bolt, sorry. Guess that's my weekend research sorted though :o) – Gareth Dackevych-Thomas Oct 29 '16 at 00:55
0

You can use the striptags filter. As example:

{{ article.body| striptags [:1] }}

Here a working example

Hope this help

Matteo
  • 37,680
  • 11
  • 100
  • 115
  • I actually saw that and tried it but then how are the editors going to format their articles with html ? – iBobb Oct 29 '16 at 10:02
0

You shouldn't need to extract the first letter if you use CSS e.g.

Template: <div class="dropcap">{{ article.body }}</div>

CSS: div.dropcap p:first-of-type::first-letter {color: #f00;}

That will alter the first letter of the first paragraph.

Ben
  • 36
  • 2