I want to use trancate filter in twig but i have the error:
The file "D:\projets\dzairdeals\config/services.yaml" does not contain valid YAML: Indentation problem in "D:\\projets\\dzairdeals\\config/services.yaml" at line 30 (near " twig.extension.text:") in D:\projets\dzairdeals\config/services.yaml (which is loaded in resource "D:\projets\dzairdeals\config/services.yaml").
When I try to add this lines to my services.yaml
twig.extension.text:
class: Twig_Extensions_Extension_Text
tags: - { name: twig.extension }
For anyone coming to this for Symfony 5:
composer require twig/string-extra
composer require twig/extra-bundle
Then you can use the truncate filter like so:
{{ project.title|u.truncate(30, '...') }}
Truncate filter is passed a length and an optional string to append to the end if truncated.
u. meaning the string on the left is encapsulated in a Unicode object, see https://twig.symfony.com/doc/2.x/filters/u.html
Make sure twig/extensions is installed:composer require twig/extensions, if so, you should see a config file auto-generated containing:
#config/packages/twig_extensions.yaml
services:
_defaults:
public: false
autowire: true
autoconfigure: true
# Uncomment any lines below to activate that Twig extension
#Twig\Extensions\ArrayExtension: null
#Twig\Extensions\DateExtension: null
#Twig\Extensions\IntlExtension: null
#Twig\Extensions\TextExtension: null
A correct indentation for your yaml file could be :
twig.extension.text:
class: Twig_Extensions_Extension_Text
tags:
- { name: twig.extension }
or
twig.extension.text:
class: Twig_Extensions_Extension_Text
tags: [twig.extension]
Related
While installing serverless with following command
sls plugin install -n serverless-alexa-skills --stage dev
I am getting an error like Your serverless.yml has an invalid value with key: "Ref"
The following is my sample serverless.yml file
plugins:
- serverless-webpack
- serverless-s3-sync
- serverless-plugin-git-variables
- serverless-alexa-skills
functions: ${file(./deploy/${opt:stage}.yml):functions}
resources: ${file(./deploy/${opt:stage}.yml):resources}
custom: ${file(./deploy/${opt:stage}.yml):custom}
outputs:
DialogflowFunctionArn:
Value:
Ref:
Got a block here. can some one help me here.
Ref is a Cloudformation intrinsic function. It needs to reference a resource. The whole outputs section is also optional, use it only if you need to reference the resources from one stack in another.
It basically says that Ref: is expecting a value. You have defined it but not assigned any value to it. If there is no use then you should remove this part from your code:
outputs:
DialogflowFunctionArn:
Value:
Ref:
Ref expects to reference something, right now you are not passing it anything to reference.
So, assuming you want the ARN of DialogflowFunction and that function config looks something like this in your functions file:
DialogflowFunction:
description: get the flow
handler: src/functions/dialog-controller.flow
events:
- http:
path: '/dialog/flow'
method: get
cors: true
Then your ref would look something like this:
outputs:
DialogflowFunctionArn:
Value:
Ref: DialogflowFunction
Ref takes the logical id of the resource for which you want to reference, in this case that is DialogflowFunction, and will return the ARN of that resource.
I looking for node module (or something else) that can parse in runtime parameters from my program into yaml files.
for example in kubernetes yamls
metadata:
name: $PROJECT_NAME
labels:
service: $SERVICE_NAME
system: $SYSTEM_ID
app_version: $PROJECT_VERSION
tier: app
There is a nice way to build new yaml or change the exist one that contain all my parameters values?
I decided to use Handlebars module
just give to the function a template with the parameters that i want to parse and the function will create new file contain all my changes
const Handlebars = require('handlebars');
const source = fs.readFileSync(`${cwd}/${file}`).toString();
const template = Handlebars.compile(source);
const contents = template({ PROJECT_NAME: `${name}`, PROJECT_VERSION: `${version}`, DOCKER_IMAGE: `${image}` });
fs.writeFileSync(`${cwd}/target/${file}`, contents);
console.log(`${file} -- Finish parsing YAML.`);
and the JSON look like
spec:
containers:
- name: {{PROJECT_NAME}}:{{PROJECT_VERSION}}
resources:
limits:
memory: "1Gi"
cpu: "1"
image: {{DOCKER_IMAGE}}
YAML doesn't always need a template as it is structured data. As long as you don't need formatting/comments, objects can be read or dumped with js-yaml.
const yaml = require('js-yaml')
const fs = require('fs')
const kyaml = {
metadata: {
name: project_name,
service: service_name,
system: system_id,
app_version: project_version,
tier: 'app',
}
}
fs.writeFile('new.yaml', yaml.safeDump(kyaml), 'utf8', err => {
if (err) console.log(err)
})
Also you could possibly be doing things that helm can already do for you with templates.
Any template engine should work but the templated values should be escaped appropriately if there is a chance the values will produce encoding errors. Because YAML is a superset of JSON, JSON.stringify can be safely used as a valid YAML escape function.
Using Mustache templates, we ensure all templated values are escaped by setting the escape function:
const mustache = require('mustache')
mustache.escape = JSON.stringify
mustache.render(template, vars)
Using Handlebars we can produce valid YAML by disabling the default escaping and providing a "json" helper:
const handlebars = require('handlebars')
const render = handlebars.compile(template, { noEscape: true })
render(vars, {helpers: { json: JSON.stringify }}))
The json helper needs to be used in the YAML template any time a value may require escaping:
metadata:
name: {{json projectName}}
labels:
version: {{buildId}}
tier: app
Without appropriate YAML escaping there could be encoding errors in the generated YAML document if values contain newlines or YAML special characters like "|". Some templating engines (eg Mustache and Handlebars) will escape values with HTML encoding by default which will also produce encoding errors if HTML special characters are present in values (eg quote which is escaped as "'").
EDIT: Dec 3 2016
Want to learn how to add custom extensions(filters) to twig? see this answer by lxg
Do you just need to find the twig equivalent for ucwords? see this answer by Javier Eguiluz
I found several posts on calling php functions from twig, that show it should be supported, however it doesn't seem to work.
{{ ucwords( item|replace({'_':' '}) ) }}
results in :l
Slim Application Error
The application could not run because of the following error:
Details
Type: Twig_Error_Syntax Message: The function "ucwords" does not exist
in "home.twig" at line 101
File:
/usr/share/dev89/html/vhosts/local/libs/vendor/twig/twig/lib/Twig/ExpressionParser.php
Line: 572
As #lxg said, it's not possible to call all PHP functions from Twig templates ... unless you want to do that and define your own filters/functions. Instead of a drawback, this is a good thing to "force" you to create good templates that don't contain too much logic.
Anyway, in this particular case, Twig already contains a filter called title which applies the "title case", which is equivalent to the ucwords() PHP function:
{{ item|replace({'_':' '})|title }}
Update: Twig 2.x comes with the capitalize filter which does exactly that.
It is not true that all PHP functions are available in Twig. Only a few Twig filters and functions go by the same names as their equivalents in PHP.
But you can easily create your own Twig extension for ucwords – filter as well as function:
<?php
namespace Acme\TestBundle\Twig;
class UcWordsExtension extends \Twig_Extension
{
public function getFunctions()
{
return [
new \Twig_SimpleFunction('ucwords', 'ucwords')
];
}
public function getFilters()
{
return [
new \Twig_SimpleFilter('ucwords', 'ucwords')
];
}
public function getName()
{
return 'ext.ucwords';
}
}
The first parameter of Twig_SimpleFunction/Twig_SimpleFilter is the name of the function/filter in Twig. The second parameter is a PHP callable. As the ucfirst function already exists, it is sufficient to pass its name as a string.
Test in Twig:
{{ "test foobar"|ucwords }} {# filter #} <br>
{{ ucwords("test foobar") }} {# function #}
Returns:
Test Foobar
Test Foobar
Why not use title filter?
I was looking for a filter that will work as like ucwords() php function and I found this title filter in Twig Documentation.
Usage example;
{{ 'i am raziul islam'|title }}
Outputs: I Am Raziul Islam
You can use the capitalize twig filter:
{{ item | capitalize }}
I've been using hiera for several weeks now and all was working fine til few days ago when i started to get that kind of message:
Error: Could not retrieve catalog from remote server: Error 400 on SERVER: Could not find data item nom in any Hiera data file and no default supplied on node d0puppetclient.victor-buck.com
Warning: Not using cache on failed catalog
Error: Could not retrieve catalog; skipping run
So i tried to make a very simple test to check if the problem came from my last code changes and i'm still getting this message. I can't get hiera variable anymore.
Below the test i made:
hiera.yaml:
---
:backends:
- yaml
:yaml:
:datadir: /etc/puppet/hieradata
:hierarchy:
- common
site.pp:
# /etc/puppet/manifests/site.pp
case $operatingsystem {
'Solaris': { include role::solaris }
'RedHat', 'CentOS': { include redhat::roles::common }
/^(Debian|Ubuntu)$/: { include role::debian }
# default: { include role::generic }
}
case $hostname {
/^d0puppetclient/: { include test }
}
test.pp:
class test{
$nom = hiera('nom')
file {"/root/test.txt":
ensure => file,
source => "/etc/puppet/test.txt.erb",
}
}
test.txt.erb:
<%= nom %>
Any idea about to fix this? I thought this could be an file access right issue, so i tried to grante access on some files (755) and it's not working...
You need to define nom in your common.yaml in order for it to hold a value. You can set a default value and conditionally create the file if you don't plan on setting it.
class test {
$nom = hiera('nom', false)
if $nom {
file { '/root/test.txt':
ensure => file,
content => template('test/test.txt.erb')
}
}
}
Notice how i used content instead of source. When using erb templates you need to specify the content using the template() function.
Using Templates
If you use source it is expecting a file rather than an erb template.
Hope this helps.
I have a language selector in my project to redirect to index page with the locale parameter {_locale}, but when the link is to default locale seted in routing.yml, the link looks different. This is my code:
I generate the link in code:
<a href="{{ path('ProjectBaseBundle_index', {'_locale': country.idlang}) }}">
...
</a>
And here is the routing.yml:
ProjectBaseBundle_index:
pattern: /{_locale}
defaults: { _controller: ProjectBaseBundle:Default:index, _locale: es }
requirements:
_locale: en|fr|de|es
This generate propertly the routes for all languages, buy for the default one looks different:
http://project.dev/app_dev.php/en
http://project.dev/app_dev.php/fr
http://project.dev/app_dev.php/de
http://project.dev/app_dev.php/?_locale=es
es is our default language code. I'm using Symfony 2.1
Anyone know How to generate identical route for the default lang?
It happens because of conditions for requirements and provided parameters in UrlGenerator - unknown parameters passed through the arguments array are automatically appended at the end of the URL as GET parameters.
Did you try to put default locale in config.yml instead of having it in defaults section of route?
Symfony-2.0:
framework:
session: { default_locale: es }
Symfony-2.1:
framework:
default_locale: es
I just discovered that it makes sense, because the parameter {_locale} does not exists for the default language, so the system appended the parameter as a GET parameter.
I found a workaround:
ProjectBaseBundle_default:
pattern: /{_locale}
defaults: { _controller: ProjectBaseBundle:Default:index , _locale: %locale% }
ProjectBaseBundle_index:
pattern: /{_locale}
defaults: { _controller: ProjectBaseBundle:Default:index }
requirements:
_locale: en|fr|de|es
and I have opened a issue in Symfony board: https://github.com/symfony/symfony/issues/5135