Возник вопрос, дорабатываю проект (изначально не мой) и стоит задача русифицировать фильтр месяца на Yii2.
Суть в следующем: В проекте есть страница с печатью документов, в который изначально передается ID шаблона с google docs где можно поправить шаблон и добавить формат для даты. Формат даты передается как токен.
К примеру токен дата передается как:
{{date|date}} // выведет 15.05.2020,
{{date|date:'d.M.Y'}} // выведет 15 May 2020,
{{date|date:'Y'}} // выведет 2020,
Как можно русифицировать токен M?
В проекте используется Latte. В Latte (vendor/latte/latte/src/Latte/Runtime/Filters.php) есть функция date
Код: Выделить всё
public static function date($time, string $format = null): ?string
{
if ($time == null) { // intentionally ==
return null;
}
if (!isset($format)) {
$format = self::$dateFormat;
}
if ($time instanceof \DateInterval) {
return $time->format($format);
} elseif (is_numeric($time)) {
$time = new \DateTime('@' . $time);
$time->setTimeZone(new \DateTimeZone(date_default_timezone_get()));
} elseif (!$time instanceof \DateTimeInterface) {
$time = new \DateTime($time);
}
return strpos($format, '%') === false
? $time->format($format) // formats using date()
: strftime($format, $time->format('U') + 0); // formats according to locales
}
Код: Выделить всё
public function render($view, $file, $params)
{
$this->html = file_get_contents($file);
$this->file = $file;
$tmpDir = Yii::$app->runtimePath . DIRECTORY_SEPARATOR . 'document';
FileHelper::createDirectory($tmpDir);
$document = new DOMDocument();
$document->registerNodeClass('DOMElement', DOMElement::class);
try {
$document->loadHTML($this->html);
} catch (ErrorException $exc) {
if (preg_match('~DOMDocument::loadHTML\(\): ID ([\S]+) already defined in Entity~', $exc->getMessage(), $matches)) {
$this->html = str_replace('id="' . $matches[1] . '"', '', $this->html);
$document->loadHTML($this->html);
}
}
/** @var DOMElement $body */
$body = $document->getElementsByTagName('body')->item(0);
$this->content = $body->innerHTML;
$this->clear();
$this->registerSource();
$this->lexVar();
$this->lexBlock();
$latte = new Engine;
Filters::$dateFormat = 'd.m.Y';
$latte->addFilter('money', function ($s) {
return number_format($s, 2, ',', ' ');
});
$latte->addFilter('spellout', function ($s) {
$r = floor($s);
$c = ceil((round($s, 2) - $r) * 100);
return Yii::$app->formatter->asSpellout($r) . ' руб. ' . sprintf("%'.02d\n", $c) . ' коп.';
});
$latte->addFilter('short', function ($s) {
$words = explode(' ', $s);
foreach ($words as $i => &$word) {
if ($i === 0) {
$word = $word . ' ';
continue;
}
$word = mb_strtoupper($word);
$word = StringHelper::truncate($word, 1, '.');
}
return join('', $words);
});
$latte->getParser()->defaultSyntax = 'double';
$latte->setTempDirectory(Yii::$app->runtimePath . DIRECTORY_SEPARATOR . 'document');
$latte->setLoader(new StringLoader([
'main' => $this->content,
]));
$this->content = $latte->renderToString('main', $params);
$this->content = str_replace('<hr style="page-break-before:always;display:none;"/>', '<div style="page-break-before:always"></div>', $this->content);
$this->content = str_replace('<hr style="page-break-before:always;display:none;">', '<div style="page-break-before:always"></div>', $this->content);
$this->content = str_replace('\n', '<br>', $this->content);
$this->content .= '<script>' . '
try {if(window.self === window.top){window.print();}} catch (e) {}' . '</script>' . "\n" . '<style type="text/css">body{margin:0;padding:0;}</style>';
$body->innerHTML = $this->content;
return $document->saveHTML();
}
Если нужны еще какие-нибудь куски кода выложить, напишите, доложу. Заранее, спасибо за внимание и помощь!)