How to test if a value is a string in a template - string

I would like to find out if it is possible and if so how, to test if a value is a string in a Go template.
I have tried the following with no success
{{- range .Table.PrimaryKeys.DBNames.Sorted }}{{ with (index $colsByName .)}}
{{ .Name }}: {{ if .IsArray }}[]{{ end }}'{{.Type}}', {{end}}
{{- end }}
{{- range $nonPKDBNames }}{{ with (index $colsByName .) }}
{{ .Name }}: {{ if .IsArray }}[]{{end -}} {
type: {{ if .Type IsString}}GraphQLString{{end -}}, # line of interest where Type is a value that could be a number, string or an array
}, {{end}}
{{- end }}
And this is the error that I get
Error: error parsing TablePaths: error parsing contents template: template: templates/table.gotmpl:42: function "IsString" not defined

With a custom function
There is no predeclared IsString() function available in templates, but we may easily register and use such a function:
t := template.Must(template.New("").Funcs(template.FuncMap{
"IsString": func(i interface{}) bool {
_, ok := i.(string)
return ok
},
}).Parse(`{{.}} {{if IsString .}}is a string{{else}}is not a string{{end}}`))
fmt.Println(t.Execute(os.Stdout, "hi"))
fmt.Println(t.Execute(os.Stdout, 23))
This will output (try it on the Go Playground):
hi is a string<nil>
23 is not a string<nil>
(The <nil> literals at the end of lines are the error values returned by the template execution, telling there were no errors.)
Using printf and %T verb
We may also do this without custom functions. There is a printf function available by default, which is an alias for fmt.Sprintf(). And there is a %T verb which outputs the argument's type.
The idea is to call printf %T on the value, and compare the result with "string", and we're done:
t := template.Must(template.New("").
Parse(`{{.}} {{if eq "string" (printf "%T" .)}}is a string{{else}}is not a string{{end}}`))
fmt.Println(t.Execute(os.Stdout, "hi"))
fmt.Println(t.Execute(os.Stdout, 23))
This will also output (try it on the Go Playground):
hi is a string<nil>
23 is not a string<nil>

Related

Inserting braces with format in python

I am trying to print this string
str = "container.insert({{ {0} ,{{ {{ {1}, {{ {2} ,{3} ,{4} , {5} }} }} }} }});"
str.format(prim_ident,country_ident,final[0],final[1],final[2],final[3])
fileWrite.write(str)
However the output of above that I get is
container.insert({{ {0} ,{{ {{ {1}, {{ {2} ,{3} ,{4} , {5} }} }} }} }});
Two problems the first problem is that i am getting double curly braces. I only want to show a single curly brace. But i read that you have to use double curly braces when u would like the curly brace to be present in the string the other problem is my format is not working (i.e) {0},{1} etc are not being replaced by their equivalent values. Can anyone please tell me what I am doing wrong ?
str.format() does modify the string in-place, you still need to save it to a variable, try adding str = :
str = str.format(prim_ident,country_ident,final[0],final[1],final[2],final[3])

Dotliquid: value from string

Is there a way to get the value from a string?
For example:
"SomeString" has the value "Edward".
Input:
{% assign variable = 'SomeString' %}
{{ variable }}
Output:
SomeString
Note: SomeString is a constructed string during runtime, so I in fact need to get the value from a string --> I can't remove the quotes in the assignment.
There is nothing in DotLiquid which allows to do that, however it is always possible to create your own Tag or to build the template at run time.
public sealed class RuntimeAssign : Tag
{
...
}
Template.RegisterTag<RuntimeAssign>("runtimeassign");

Twig - Replace chars in connected string

How can i replace some chars (Goal is a simple double slash to one slash) in a connected twig string?
{{ config_basehost ~ navigationElement.imgSrc }} // Connect 2 Strings
Replace works like:
{{ config_basehost|replace({"a": "b"}) }} // Replace all "a" with "b"
But how can i replace something in a connected string?
{{ {{ config_basehost ~ navigationElement.imgSrc }}|replace({"a": "b"}) }} // Output: http://example.com/img/cats.jpg|replace({"a":"b"})
As you see, the replace is at the end of my "generated" URL. Same as:
{{ config_basehost ~ navigationElement.imgSrc }}|replace({"a": "b"}) // Without bracers
The double slashes only occures connecting string 1 with string 2. So, string 1 has a slash at last position inside the string, and string 2 at first position. I could replace the last char or the first char from one of these strings, yeah. But that's not the question :)
{{ (config_basehost ~ navigationElement.imgSrc)|replace({"a": "b"}) }} - try this.
Use brackets. Simple :)
{{ STRING|replace("en": "ar") }}
Replaces all occurrences of 'e' and 'n' in a string
{{ STRING|replace({"en": "ar"}) }}
Replaces all occurrences of 'en' with ar in a string

Check if string variable is null or empty, or full of white spaces

How can I check if a string variable is null or empty, or full with space characters in Twig? (Shortest possible, maybe an equivalent to CSharp's String.IsNullOrWhiteSpace() method)
{% if your_variable is null or your_variable is empty %}
should check whether the variable is null or empty.
If you want to see if it's not null or empty just use the notoperator.
{% if foo is not null and foo is not empty %}
See the docs:
empty
null
"is" operator
logical operators like "not"
Perhaps you might be interested in tests in twig generally.
There are already good answers, but I give my 2 cents too:
{% if foo|length %}
I was inspired by #GuillermoGutiƩrrez's filter trick.
But I think |length is safer as the "0"|trim expression will evaluates to false.
References :
length
codepad
boolval
I'd rather use just trim and empty:
{% if foo|trim is empty %}
{% if foo|trim is not empty %}
empty evaluates to true if the foo variable is:
null
false
empty array
empty string
{% if foo|trim %} seems to be enough (assuming that foo is the variable to check). If foo is not null, trim removes whitespaces. Also, if handles empty string or null as false, and true otherwise, so no more is required.
References:
trim

Coding Implode In Twig

How can one use the equivalent of the implode function in a Twig environment?
For example, the contents of the variable $data1 = "input your name" and the variable $data2 = "input your address".
How to create a variable $result = "input your name, input your address" in Twig?
I'm guessing you're looking for the join filter. It works exactly like implode does in php. Quoting from the manual page:
The join filter returns a string which is the concatenation of the items of a sequence:
{{ [1, 2, 3]|join }}
{# returns 123 #}
The separator between elements is an empty string per default, but you can define it with the optional first parameter:
{{ [1, 2, 3]|join('|') }}
{# returns 1|2|3 #}

Resources