How to set default in case of undefined variable in template for cookiecutter? - cookiecutter

I am using cookiecutter 1.7.3
I want a way to have defaults in case an undefined variable in the template.
What I tried
using default filter in jinja
"github_username": "{{ cookiecutter.github_repo.owner.login|default('Your GitHub username here', true) }}"
or boolean
"github_username": "{{ cookiecutter.github_repo.owner.login or 'Your GitHub username here' }}"
None of this works. I still get undefined variable in template error.
Can advise?

Since this question remains unanswered, adding something that worked for me. I used the is defined expression to check if the key of the object exists since cookiecutter threw an error if the key didn't exist. If you're sure the key will not be undefined and exists and you need to check for a value, you can do something like:
"yay" if cookiecutter.github_repo.owner == "Dr. Acula" else ":("
So in this case, it would be something like this:
"github_username": "{{ cookiecutter.github_repo.owner.login if cookiecutter.github_repo.owner.login is defined else "Your GitHub username here" }}"

Related

expected token 'Identifier' and actual 'LeftSquareBracket' in Arm Template when parsing if statment

I'm trying to set a variable in the variables section of an ARM template using the if function.
in the parameter section I've definded a parameter that is been filled by a parameter file. let's call it condition:
"condition": {
"type": "bool",
"defaultValue": false}
now in the variables section I would like to define a variable that if condition is true then var = ["1","2","3"] else var = [] an empty array.
I've tried:
"var" : "[if(parameters('condition'),[\"1\",\"2\",\"3\"],[])]"
"var" : "[if(parameters('condition'),['1','2','3'],[])]"
"var" : "[if(parameters('condition'),array(['1','2','3']),array([]))]"
all with the same result expected token 'Identifier' and actual 'LeftSquareBracket'
error thrown.
of course I can solve it in a similar way to:
"var0" : ["1","2","3"],
"var1" : [],
"var" : "[if(parameters('condition'),variables('var0'),variables('var1')]"
but that would lead to two dummy variables and an uglier code, and I would really like to avoid it.
trying to deploy from azure CLI.
It is surly a syntax error but I just can't figure it out.
Thanks in advance for your help!
Well, Turn's out the answer is just to use the built-in json() function.
I've solved it with:
"var" : "[if(parameters('condition'),json('[\"1\",\"2\",\"3\"]'),json('[]'))]"

How can i use twig truncate in Symfony 4

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]

How to call ucwords in twig?

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 }}

Jade with Express - how to disable ReferenceError

i want replace empty string instead of ReferenceError. following code :
p #{data.data.data}
ReferenceError occured when render template that i want disable it.
Stumbled onto the same thing, but passing an empty object felt wrong. I suggest handling the possibility in the template with something like:
- if(data)
p #{data.data.data}
- else
p No data for you!
Or specify a placeholder inline
p #{data.data.data ? data.data.data : 'No data'}
Pass an empty object if there is no value when rendering:
res.render('view/index', {data: your_data_variable || {} });

Undefined attribute in jade template engine

I'm simply trying to display a value in an input field with Jade (0.20.3) and Express (2.5.8):
input(name='username', type='text', id="username", value=username)
It is quite simple, but this throws an error when the value is undefined:
username is not defined
However, the documentation indicates:
When a value is undefined or null the attribute is not added, so this is fine, it will not compile 'something="null"'.
Is there something that I would have done wrong?
Short answer: use locals.someVar if you're not sure that someVar exists.
Longer Answer:
I think that Brandon's initial answer and last comment are correct (though the #{...} syntax isn't needed), but to elaborate a bit: There's a difference between passing in an a variable (technically, an object property) with a value of undefined, and not passing that variable at all.
Because Jade transforms your template into JS source and evals it (in the context of a with block), you have to make sure that you're not referring to any variables that haven't been passed in, or they'll be . This blog post has some background on undefined vs undeclared variables and ReferenceError.
Your Jade template should work correctly if you do one of these things:
// ok, even if req.session.username is not defined
res.render('index', { username: req.session.username })
// ditto
res.local('username', req.session.username);
res.render('index')
But these won't work:
res.locals(req.session) //if no username property exists
res.render('index', { /* no username */ } )
If it's not practical to manually pass in each parameter you might want to refer to, you can refer to the variable in your template as properties on the locals object (e.g. locals.username)
You have to make sure you're passing username into the Jade template. Example:
app.get('/', function (req, res) {
res.render('index', { title:'APP NAME', username: req.session.username });
});
Also, you would call it like this in the Jade template: #{username}

Resources