Twig Date Filter Issue | Wrong output - symfony

I am working on Symfony application and using Twig for layout.
I facing wrong output issue i google it but can't find the solution.
I have date & time 201801031400 I used this
{{ val.start_date|date("m/d/Y") }}
but get the wrong output 10/27/8364
When i used this {{ "now"|date("m/d/Y") }} it give me correct output
Thanks in Advance!

You need to a function to Twig to achieve this, you can see how to register an extension here
TwigExtension
namespace My/Project/Twig/Extensions
class ProjectTwigExtension extends Twig_Extension {
public function getFunctions() {
return array(
new Twig_SimpleFunction('convert_api_date', function($date) {
return new DateTime($date);
}),
);
}
public function getName() {
return 'ProjectTwigExtension'; //this is mandatory
}
}
twig
{{ convert_api_date('201801031400') | date('d/m/Y') }}
{{ convert_api_date('201801031400') | date('H:i') }}

Above answer will perfectly alright i just my solution code too.
First Twig date filter not support the 201801031400. so for this you have to make your own extension.
How to create twig extension create twig extention
<?php
// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;
class DateParserFilter extends \Twig_Extension
{
public function getFilters ()
{
return array(
new \Twig_SimpleFilter('parse_date', array($this, 'parseDate'))
);
}
public function parseDate ($string, $formats)
{
if (is_string($formats))
{
$formats = array($formats);
}
foreach ($formats as $format)
{
$dateTime = \DateTime::createFromFormat($format, $string);
if ($dateTime !== false)
{
return $dateTime;
}
}
return $string;
}
public function getName ()
{
return "parse_date";
}
}
after this use your own extension filter first then use twig builtin date filter example show below :)
{{ val.start_date | parse_date(["YmdHi", "d/m/Y H:i"]) | date("M d, Y") }}
Its depend what you have in my case i have [2018][01][03][14][00] = [Y][m][d][H][i]
hope it will help you :)
source of this extension - link

You have to divide your unix timestamp value by 1000.
I'm still not sure with what it's related, but this operation is used by authoritative online converters, that most likely faced the same problem.
I came to this conclusion thanks to this answer Converting a UNIX Timestamp to Formatted Date String.
Below is the proof that your unix timestamp is correct:
1) from www.freeformatter.com
2) from www.epochconverter.com
The data is slightly different due to the time zone. It must be taken into account.
Write in the comments, why should I divide by 1000. I myself will be interested.

Related

Substring Count in Twig

I am looking to use substr_count in Twig, does anything exist already? I want to perform something like this;
<?php
$text = 'This is a test';
echo strlen($text); // 14
echo substr_count($text, 'is'); // 2
I can do an extension but it seems this might be something built in already that I have missed.
How about this?
{%set count = text|split('is')|length-1 %}
This doesn't exist in the list of Twig functions or filters.
You'll have to write your own custom function/filter or try a package (note; I've never used this package so can't comment on it, but was on the first page of Google results).
I went for an extension
namespace AppBundle\Twig;
class SubStrCountExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('substr_count', array($this, 'substr_count')),
);
}
public function getName()
{
return 'substr_count_extension';
}
public function substr_count($str, $char)
{
return substr_count($str, $char);
}
}
And in services.yml
app.twig_extension.substr_count_extension:
class: AppBundle\Twig\SubStrCountExtension
tags:
- { name: twig.extension }
I use solution in Symfony 3.2.8 but in the description does not say this block of code should is inside : services
If you does not make show this error:
There is no extension able to load the configuration for .....
This code should is inside services this is correct:
services:
app.twig_extension.substr_count_extension:
class: AppBundle\Twig\SubStrCountExtension
tags:
- { name: twig.extension }
Finally, the correct use in twig is:
tu placa es: {{substr_count(datos.picoyplaca,4)}}
Regards

Split function not working in Twig

what i Need :
Split the string.
i Need first Character from the String.
if the string certain character limit i like to show only first name not by(...).
ex: ankit mishra pandit aggarwaal.
- so i just want only ankit.
- if its is ankit mishra its ok.
* otherwise show Full Name.
Here is the twig code:
{%if item.metadata.name |length < 20 %}
{% set foo = item.metadata.name|split(',') %}
{{ foo[0] }}
{%else%}{{WordLimit(item.metadata.name,20,10)}} ..
{%endif%}
output im getting :
Deepak Singh.
i have refer Source: Twig Split filter http://twig.sensiolabs.org/doc/filters/split.html.
where i have done wrong.
I think the best solution is to write a twig extension.
See http://symfony.com/doc/current/cookbook/templating/twig_extension.html
class AcmeExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('first_word', array($this, 'first_word')),
);
}
public function first_word($word)
{
$words = explode(' ', $word);
$first_word = $words[0];
...
return $first_word;
}
public function getName()
{
return 'acme_extension';
}
}
And if your twig file :
{{item.metadata.name | first_word }}

Displaying currency symbol in twig

How can I display the currency symbol in twig? I saved the numeric value of the symbol like:
for EURO : €
for DOLLAR: $
When I render these values, & is converted to & and the currency symbol does not show. Any idea will be greatly appreciated. Thank you.
To do it well, you've to add a function or a filter which is called as a helper to render currency symbols within your twig templates.
To use the following function,
{{ currency('en_US') }}
You've to add a twig extension as follow,
xxx.twig.your_extension:
class: XXX\YourBundle\Twig\YourExtension
tags:
- { name: twig.extension }
You've then to add a currency function,
namespace XXX\YourBundle\Twig;
class YourExtension extends \Twig_Extension
{
public function getFunctions() {
return array(
'currency' => new \Twig_Function_Method($this, 'currencyFunction'),
);
}
public function currencyFunction($locale) {
$formatter = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
$symbol = $formatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);
return $symbol;
}
public function getName() {
return 'your_extension';
}
}
I figured it out. When rendering, I need to use the raw filter of twig.
It is an old thread, but for the new people coming here, Twig has now an extension for the currency symbols (with new filters |currency_symbol ) as you can see in the documentation

Twig CamelCase Filter in Symfony2

So I'm pretty new to Symfony2 and I'm trying to use the camelize filter in a twig template. However when I request the page I get an error saying that the filter doesn't exist:
The filter "camelize" does not exist in ::base.html.twig
Here's the line from my template file:
{{ 'hello world' | camelize }}
The filter is listed on Twig's quick reference page.
I'm confused, doesn't Symfony2 support all of twig's filters? There seem to be quite a few missing, why? And if it doesn't support them, then is there any way to add the missing ones in?
Thanks in advance!
edit Ok, so it turns out I'm retarded and I need to remember to check that I've actually got the right git project. No wonder I was confused. Thanks replies!
Symfony 2 has title filter for camel case use
{{ entity.yourstring | title }}
to camel case your string
Your link points to a fork on GitHub, meaning a modified copy of the original project. The original project is https://github.com/fabpot/Twig.
There is no camelize filter in Twig. Built-in filters are here. You can write your own camilize filter (it's easy, actually...) following this tutorial: How to write a custom Twig Extension.
EDIT: just for fun, you can write something like:
class MyTwigExtension extends Twig_Extension
{
public function getFilters()
{
return array(
'camelize' => new Twig_Filter_Method($this, 'camelizeFilter'),
);
}
public function camelizeFilter($value)
{
if(!is_string($value)) {
return $value;
}
$chunks = explode(' ', $value);
$ucfirsted = array_map(function($s) { return ucfirst($s); }, $chunks);
return implode('', $ucfirsted);
}
public function getName()
{
return 'my_twig_extension';
}
}
Note that this is a quick and dirty filter! Take a look at the built-in filters to learn best practice!
The filter you're looking for is named "title": http://twig.sensiolabs.org/doc/filters/title.html
Here is the best solution by default in Craft CMS 3
Craft 3 now has a |camel filter for twig
https://docs.craftcms.com/v3/dev/filters.html#camel
{{ 'foo bar'|camel }}
{# Output: fooBar #}

Twig: show the name of the months based on the current locale

I'm just trying to show the name of the months based on the current locale.
{{ event.date|date('F') }}
but the months are always shown in english...
I have tried this code below I found here, but the result is the same...
class Helper_Twig extends Twig_Extension
{
public function getFilters()
{
return array(
'datetime' => new Twig_Filter_Method($this, 'datetime')
);
}
public function datetime($d, $format = "%B %e")
{
if ($d instanceof \DateTime) {
$d = $d->getTimestamp();
}
return strftime($format, $d);
}
public function getName()
{
return 'Helper';
}
}
NOTE: In the controller I'm checking the current locale using $request->getLocale and it corresponds to the locale parameter I'm switching in parameters.yml.
What is the problem?
Since you defined datetime TwigFilter, you don't have to call {{ event.date|date('F') }}
Instead, you should call this {{ event.date|datetime('%B') }}
You can use SonataIntlBundle to handle localized date representation. Intl library needs to be installed though.
You probably haven't installed the PHP intl-library in your PHP. http://php.net/manual/de/book.intl.php
If you have installed the IntlExtension you can use format_datetime with custom pattern.
{{ event.date|format_datetime(pattern="MMMM") }}
docs:
https://twig.symfony.com/doc/3.x/filters/format_datetime.html
https://unicode-org.github.io/icu/userguide/format_parse/datetime/#datetime-format-syntax

Resources