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!?
You can just do this:
{{ variable[:1]|upper ~ variable[1:] }}
from https://github.com/twigphp/Twig/issues/1652
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"
You can create a new filter that return your string using the php function ucfirst
.
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"
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With