4

I know how to get the first letter of a string in TWIG

<p>The first letter is {{someString | first}}</p>

With an HTML string like

<p>This is a sting</p>

The above would return '<'

Adding 'Raw'/'escape' ends up to the same result.

I need to display that string as HTML ( like with Raw ) but get the first letter ( in the case above case 'T').

Am I using the filter in the incorrect order ?

Anyone knows ?

Many thanks ahead

@Matteo's answer is already close but not quite exactly what I wanted . I may have formulated my question wrongly. Sorry.

So If I had a string like this

<p>This is a <strong>string</strong></p>

Using raw would give

This is a string

Now what I really need is to get the first letter (T) to do something with it like adding tags around it

<span>T</span>his is a <strong>string</string>

while still keeping the rest of the HTML inside . Striptags remove all the tags in the string and return a plain string without the HTML part. I hope I formulated it right.

R.Damasinoro
  • 381
  • 2
  • 20
  • Hi there. If you think @Matteo 's answer answered your question (which I think it did), can you mark it as the correct answer. Thanks! – Alvin Bunk Sep 09 '16 at 16:24
  • It's close but not quite what I'm looking for – R.Damasinoro Sep 10 '16 at 05:15
  • Use CSS `p::first-letter`. – malcolm Sep 10 '16 at 05:53
  • Are you able to click `edit` on your post and re-word your question correctly as per your comment to @Matteo 's post? If not, maybe post a new question. Reading your comment, I still don't understand what you need. Why does `String` have to be bolded - it's not clear. – Alvin Bunk Sep 10 '16 at 06:01

2 Answers2

5

You could use the striptags filter:

<p>The first letter is {{someString|striptags | first}}</p>

Here a working solutions

Hope this help

Matteo
  • 37,680
  • 11
  • 100
  • 115
  • This is alreay a great start But I may have wrongly formulated my question ( very sorry ) What I really meant was with `

    This is a String

    `, I'd like to get the first letter and display the `String ` as bold . Which striptags does not allow as it remove all the html string. Is there a way to only remove the first tags ?
    – R.Damasinoro Sep 10 '16 at 05:03
0

How about this:

{% set someString = "This is a <strong>String<strong>"%}

<span>{{someString|striptags|first}}</span>{{someString|slice[4:]|raw}}

You can try in twigFiddle: http://twigfiddle.com/pk10ip

Alvin Bunk
  • 7,621
  • 3
  • 29
  • 45