16

I have a variable with this content "i want HTML"

When I make capitalize {{ variable|capitalize }} the sentence is: "I want html"

How can I write only the FIRST letter of the sentence big in TWIG and the others stay like they are!?

Zwen2012
  • 3,360
  • 9
  • 40
  • 67

11 Answers11

24

You can just do this:

{{ variable[:1]|upper ~ variable[1:] }}

from https://github.com/twigphp/Twig/issues/1652

Erliz
  • 341
  • 2
  • 3
10

You can create a new filter that return your string using the php function ucfirst.

mykiwi
  • 1,671
  • 1
  • 19
  • 35
  • Right, I created an own extension like its shown here: http://symfony.com/doc/current/cookbook/templating/twig_extension.html – Zwen2012 Jul 03 '15 at 07:27
  • Definitely a way to go, although I had some problems with `ucfirst` before (didn't work, gave up ultimately) – Jovan Perovic Jul 03 '15 at 08:45
6

Just to illustrate a good twig practice solution, you can create a custom Utilities Twig Extension and consider Multibyte String (mb) for strings starting with accents, to work properly:

use Twig_SimpleFilter;

class UtilitiesExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new Twig_SimpleFilter('ucfirst', 
                array($this, 'ucFirst'), array('needs_environment' => true)
            ),
        );
    }

    public function ucFirst(Twig_Environment $env, $string)
    {
        if (null !== $charset = $env->getCharset()) {
            $prefix = mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset);
            $suffix = mb_substr($string, 1, mb_strlen($string, $charset));
            return sprintf('%s%s', $prefix, $suffix); 
        }
        return ucfirst(strtolower($string));
    }
}

Then you can call such filter from a twig file in the way. Accents even work:

{{ 'étudiant de PHP' | ucfirst }}

Results in: "Étudiant de PHP"

Samuel Vicent
  • 991
  • 10
  • 16
4

ucfirst is Ok but doesn't handle accents correctly. So my ucfirst filter looks like that:

/**
 * ucfirst with handling of accents.
 *
 * @param string $value
 * @param string $encoding
 *
 * @return string
 */
public function ucfirst($value, $encoding = 'UTF8')
{
    $strlen = mb_strlen($value, $encoding);
    $firstChar = mb_substr($value, 0, 1, $encoding);
    $then = mb_substr($value, 1, $strlen - 1, $encoding);

    return mb_strtoupper($firstChar, $encoding) . $then;
}

-

$test1 = $this->container->get('app.twig.text.extension')->ucfirst('i want HTML');
$test2 = $this->container->get('app.twig.text.extension')->ucfirst('éllo');
dump($test1, $test2); die();

Will output:

"I want HTML"
"Éllo"

The same with ucfirst will output:

"I want HTML"
"éllo"
COil
  • 7,201
  • 2
  • 50
  • 98
4

You can create a filter very easily for ucfirst():

//in PHP - during setup
$twig->addFilter(new \Twig_SimpleFilter('ucfirst', 'ucfirst'));

//in Twig usage
{% set variable = 'i want html' %}
{{ variable|ucfirst }} //output: "I want html"

You can create a filter if you intend to use strtoupper() on "HTML"

IROEGBU
  • 948
  • 16
  • 33
1

You should select the first word of the sentence and just capitalize only it:

{% set foo = "i want HTML" | split(' ', 2) %}
{{ foo[0] | capitalize }} {{ foo[1] }}{% set foo = "i want HTML" | split(' ', 2) %}
{{ foo[0] | capitalize }} {{ foo[1] }}

Hope to be helpful! See a sample here: link

Tony H
  • 33
  • 7
  • WHe I have a sentence like "back to HTML" the output with your suggest is "Back". The other words are eleminated – Zwen2012 Jul 03 '15 at 06:34
  • Ok, sorry, you should append the string remaining. Try this way: {% set foo = "I want html" | split(' ', 2) %} {{ foo[0] | capitalize }} {{ foo[1] }} – Tony H Jul 03 '15 at 06:40
  • The problem is that it doesnt work with only one word. So there is an error because key "1" does not exist. I think its too complicated in twig for only writing the first letter in uppercase – Zwen2012 Jul 03 '15 at 06:47
  • you would be better of with just doing a bit more work and writing a filter twig extension to do that - especially if you plan to use this in multiple occasions – ejuhjav Jul 03 '15 at 06:50
  • mmh... it's quite strange... I've tryed this: {% set foo = "i want HTML" | split(' ', 2) %} {{ foo[0] | capitalize }} {{ foo[1] }} and it works pleasde see http://jsfiddle.net/fzNNT/18/ – Tony H Jul 03 '15 at 06:54
  • Yes i twokrs, but when i only have one word like "hello", this doesnt work – Zwen2012 Jul 03 '15 at 07:03
1

Twig_SimpleFilter is deprecated. I have created a working solution that uses the current Twig_Filter and handles accents (taken from COil code). The example demonstrates Twig custom filter in a standalone application.

<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);
$twig->addFilter(new Twig_Filter('accFirst', 'accFirst'));

$sentence = 'šumivé víno';

echo $twig->render('customfilter.html.twig',
    ['sentence' => $sentence]);

function accFirst($value, $encoding = 'UTF8')
{
    $strlen = mb_strlen($value, $encoding);
    $firstChar = mb_substr($value, 0, 1, $encoding);
    $rest = mb_substr($value, 1, $strlen - 1, $encoding);

    return mb_strtoupper($firstChar, $encoding) . $rest;
}

The following is the template file. The template file is located in the templates directory.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom filter</title>
</head>

<body>  

    <p>
     {{ sentence | accFirst }} 
    </p>      

</body>

</html>
Jan Bodnar
  • 10,969
  • 6
  • 68
  • 77
0

Simple solution with native code is:

{{ variable|first|capitalize ~ variable|slice(1) }}
g.sus
  • 1
  • 3
0

You may try this:

{{ variable | title }}

It will give you Output:

I Want Html

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 10 '22 at 11:48
0

Here is a easy Solution:

{{ variable|title|replace({ 'Html': 'HTML' }) }}

Output:

I Want HTML
-3

The following solution will work for any phrase, but it will only fix the "HTML" word and not other acronyms that may need to be fixed too:

{{ variable|capitalize|replace({ 'html': 'HTML' }) }}
Javier Eguiluz
  • 3,987
  • 2
  • 23
  • 44
  • No, that won't work: the rest of the string should stay as given, but `capitalize` will lowercase everything – Nico Haase Mar 10 '20 at 14:09