2

I'm trying to find a method of escaping characters in Craft's DateTime object.

This is the output I'm trying to achieve: 16th January 2016

This is what I've tried: {{ article.postDate.format('j\<\s\u\p\>S\<\/\s\u\p\> F Y') }}

This is the output: 16&lt;00000000p&gt;th<!--00000000p--> January 2016

I can achieve the output by appending output together but there has to be a better way of achieving this than the following:

{{ article.postDate.format('j') }}<sup>{{ article.postDate.format('S') }}</sup> {{ article.postDate.format(' F Y') }}

Any pointers to documentation would be appreciated.

3 Answers 3

5

After trial and error I figured out you can escape characters using double backslash.

{{ article.postDate.format('j\\<\\s\\u\\p\\>S\\<\\/\\s\\u\\p\\> F Y') | raw }}

Outputs: 14<sup>th</sup> January 2016

In search of documentation I found a mention of double-escaping regular expressions due to Twig auto-escaping \. At this point I'm guessing this works for most Craft-Twig functions.

3

Try the Twig date filter instead:

{{ article.postDate|date('jS F Y') }}

to wrap the ordinal in <sup>:

{{ article.postDate|date('j') }}<sup>{{ article.postDate|date('S') }}</sup>
{{ article.postDate|date('F Y') }}

if you think it's to ugly for use in your templates, consider "hiding" it in a macro.

1
  • I tried that as well, but I'm looking to put a sup element around the ordinal suffix. I'd do this using the date function by escaping the characters. Commented Jan 16, 2016 at 16:34
1

If you're using Craft 3, the Typogrify plugin will do the <sup> on ordinal numbers automatically for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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