Using Eleventy with Nunjucks, and need to check if a front matter field is empty and if a string is empty. It would be the same thing as isEmpty() in JS. Does Nunjucks support this functionality? It seems like a pretty simple and common feature, but I've looked all over the docs and StackOverflow but can't find any mention or example.
Thanks :)
I tested like so:
---
name: ray
age:
---
{% if age %}
age has a value
{% else %}
age has NO value
{% endif %}
And it worked as expected, I got: "age has NO value".
I am writing a layout template for a Hugo generated post/page. The .yaml header is
image:
- post/mytitle/image.jpg
The template incorporates the variable in Hugo as
{{ .Params.Image }}
When served, the variable is returned as
[post/mytitle/image.jpg]
My html then becomes
<img src="[post/mytitle/image.jpg]"/>
which is 404 in the browser. I've tried a number of Hugo functions to no avail like {{ trim .Param.Image "[]" }} and {{ subset .Params.Image 1 -1 }} and {{ print .Params.Image }}. Each time Hugo returned the error: "error calling substr: unable to cast []string{"post/mytitle/image.jpg"} of type []string to string".
How do I get the variable to return the string without the brackets, or alternatively, how do I omit the brackets from the string?
In Go template, you access an item in a slice with index:
{{ index .Params.Image 0 }}
The question is why the value is a sequence in the first place. You could simply do
image:
post/mytitle/image.jpg
Then you could keep the original syntax since it is now a simple value, not a sequence.
If you want to possibly include multiple images, you'd do
{{ range .Params.Image }}<img src="{{.}}">{{ end }}
Then you can have
image:
- post/mytitle/image.jpg
- post/mytitle/anotherimage.jpg
I have defined some filters and use it very often. I need to do some A/B tests and for this in some situations some of filters should work in different way.
Easiest way to do this would be create a variable in template which store a filter name. something like this:
{% set filter_name = 'some_name' %}
{{ my_value|filter_name }}
But when I try this, I get an error:
TemplateAssertionError: no filter named 'filter_name'
Please help me to find a solution.
By doing {% set filter_name = 'some_name' %}, you have create a string variable named "filter_name". You should create a filter which takes one more argument on basis of which it decides what to do.
{% set filter_name = 'some_name' %}
{{ my_value|myfilter(filter_name) }}
def myfilter(value, filtername):
if(filtername is 'twice')
return value*2
else
.....
Anyone knows how to concatenate strings in twig? I want to do something like:
{{ concat('http://', app.request.host) }}
This should work fine:
{{ 'http://' ~ app.request.host }}
To add a filter - like 'trans' - in the same tag use
{{ ('http://' ~ app.request.host) | trans }}
As Adam Elsodaney points out, you can also use string interpolation, this does require double quoted strings:
{{ "http://#{app.request.host}" }}
Also a little known feature in Twig is string interpolation:
{{ "http://#{app.request.host}" }}
The operator you are looking for is Tilde (~), like Alessandro said, and here it is in the documentation:
~: Converts all operands into strings and concatenates them. {{ "Hello
" ~ name ~ "!" }} would return (assuming name is 'John') Hello John!. – http://twig.sensiolabs.org/doc/templates.html#other-operators
And here is an example somewhere else in the docs:
{% set greeting = 'Hello' %}
{% set name = 'Fabien' %}
{{ greeting ~ name|lower }} {# Hello fabien #}
{# use parenthesis to change precedence #}
{{ (greeting ~ name)|lower }} {# hello fabien #}
In this case, where you want to output plain text and a variable, you could do it like this:
http://{{ app.request.host }}
If you want to concatenate some variables, alessandro1997's solution would be much better.
{{ ['foo', 'bar'|capitalize]|join }}
As you can see this works with filters and functions without needing to use set on a seperate line.
Whenever you need to use a filter with a concatenated string (or a basic math operation) you should wrap it with ()'s. Eg.:
{{ ('http://' ~ app.request.host) | url_encode }}
You can use ~ like {{ foo ~ 'inline string' ~ bar.fieldName }}
But you can also create your own concat function to use it like in your question:
{{ concat('http://', app.request.host) }}:
In src/AppBundle/Twig/AppExtension.php
<?php
namespace AppBundle\Twig;
class AppExtension extends \Twig_Extension
{
/**
* {#inheritdoc}
*/
public function getFunctions()
{
return [
new \Twig_SimpleFunction('concat', [$this, 'concat'], ['is_safe' => ['html']]),
];
}
public function concat()
{
return implode('', func_get_args())
}
/**
* {#inheritdoc}
*/
public function getName()
{
return 'app_extension';
}
}
In app/config/services.yml:
services:
app.twig_extension:
class: AppBundle\Twig\AppExtension
public: false
tags:
- { name: twig.extension }
In Symfony you can use this for protocol and host:
{{ app.request.schemeAndHttpHost }}
Though #alessandro1997 gave a perfect answer about concatenation.
Quick Answer (TL;DR)
Twig string concatenation may also be done with the format() filter
Detailed Answer
Context
Twig 2.x
String building and concatenation
Problem
Scenario: DeveloperGailSim wishes to do string concatenation in Twig
Other answers in this thread already address the concat operator
This answer focuses on the format filter which is more expressive
Solution
Alternative approach is to use the format filter
The format filter works like the sprintf function in other programming languages
The format filter may be less cumbersome than the ~ operator for more complex strings
Example00
example00 string concat bare
{{ "%s%s%s!"|format('alpha','bravo','charlie') }}
--- result --
alphabravocharlie!
Example01
example01 string concat with intervening text
{{ "The %s in %s falls mainly on the %s!"|format('alpha','bravo','charlie') }}
--- result --
The alpha in bravo falls mainly on the charlie!
Example02
example02 string concat with numeric formatting
follows the same syntax as sprintf in other languages
{{ "The %04d in %04d falls mainly on the %s!"|format(2,3,'tree') }}
--- result --
The 0002 in 0003 falls mainly on the tree!
See also
http://twig.sensiolabs.org/doc/2.x/filters/format.html
https://stackoverflow.com/tags/printf/info
To mix strings, variables and translations I simply do the following:
{% set add_link = '
<a class="btn btn-xs btn-icon-only"
title="' ~ 'string.to_be_translated'|trans ~ '"
href="' ~ path('acme_myBundle_link',{'link':link.id}) ~ '">
</a>
' %}
Despite everything being mixed up, it works like a charm.
The "{{ ... }}"-delimiter can also be used within strings:
"http://{{ app.request.host }}"
This more or less complex phrase to translate in my Django template is:
This site is owned by "The Company Name" and is maintained by partner organizations.
Is it as simple as:
{% trans "This site is owned by "The Company Name" and is maintained by partner organizations." %}
Thank you.
From a translation point of view, as long as the translator translates the entire string just like that, you are OK. By that I mean that they put the href around the company name.
From a technical point of view you might want to check out this page: http://docs.djangoproject.com/en/dev/topics/i18n/internationalization/
trans template tag
The {% trans %} template tag translates either a constant string (enclosed in single or double quotes) or variable content:
<title>{% trans "This is the title." %}</title>
<title>{% trans myvar %}</title>
So it appears