Render value to tenths place in nunjucks template? - nunjucks

Using the round() filter I can achieve the correct precision to the tenths place as in
{{ value | round(1) }}
however I still want to display the tenths place if value is zero or a whole integer. (0.0 instead of 0, 3.0 instead of 3)
Is there a different method or other way to render all values to the tenths place?

Add you own filter
var env = nunjucks.configure(...
env.addFilter('round1', function(num) {
if (!isNaN(num))
return '???';
return parseFloat(num).toFixed(1);
});
Usage
{{ value | round1 }}

Here is the logic for the custom filter since the round filter will not maintain a tenths place for zero or whole integers:
nunjucks.configure().addFilter('tenths', function(num) {
return parseFloat(num).toFixed(1);
});
Then usage is the same as any filter:
{{ num | tenths }}

Related

Displaying numeric values with 9 decimal points in liquid templates using DotLiquid

I'm trying to display a numeric value of 0.733675715 using liquid templates.
Following code
{%- assign rate = 0.733675715 -%}
{{ rate }}
Results in: 0.7336757
I could not find a way to:
convert numeric value to string
force liquid to display all decimal places
--edit
Note: DotLiquid is used by Azure logic apps integration accounts to do transformations between JSON/XML/Text
I found the issue in dotLiquid library.
The fix can be found in this PR: https://github.com/dotliquid/dotliquid/pull/353.
Basically, in the assign statement, dotliquid is parsing the value as float[1], hence the lost precision.
// Floats.
match = FloatRegex.Match(key);
if (match.Success)
{
// For cultures with "," as the decimal separator, allow
// both "," and "." to be used as the separator.
// First try to parse using current culture.
if (float.TryParse(match.Groups[1].Value, NumberStyles.Number, FormatProvider, out float result))
return result;
// If that fails, try to parse using invariant culture.
return float.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
}
https://github.com/dotliquid/dotliquid/blob/b415f6aaa5b66fdbfa9c5d676427c7663c1e98e3/src/DotLiquid/Context.cs#L347

Converting Gigabytes to bytes in helm templates

I have a chart for kafka, that has a pvc size defined in its values file like so: 20Gi. I also have a configmap, that has a definition that it takes in bytes, like so: log.retention.bytes=21474836480.
I'm trying to get my chart to use the same value defined in size in the values file, in the configmap (hopefully, do some arithmetics on it before, like taking away a constant value to reserve some extra space)
I've been looking for a while to see if there is such a function built in to helm templates, or a way to create my own functions, with not much luck.
Ideally, I'm looking for something like this:
log.retention.bytes={{ .Values.persistence.size | convert-to-bytes | substract 10000 }}
You can use the div Sprig function. For example, you could do:
{{ div .Values.persistence.size 1024 }}
If you'd like to perform a subtraction on the result, you can use the sub function. For example:
{{ sub (div .Values.persistence.size 1024) 10000 }}
I've managed to get results I need with this code:
log.retention.bytes={{ subf (trimSuffix "Gi" .Values.persistence.size | mulf 1073741824) 10000 | floor }}
subf and mulf are used because value in "Gi" can often be floor not intger and sub and mulf are supposed to be used only with integers.

function in a model that returns a boolean fails to return anything in a blade view if false

I have a function in a model that can return either true or false.
I use this function inside a view and first thing I discovered when I called it is
{{ Setting::isDesktop() }}
that it outputs 1 instead of true if I do that inside blade file. If I do dd({{ Setting::isDesktop() }}) then it will print true or false.
Second thing that is giving me a problem is that, if the value is false then nothing is printed when doing this from blade file. I need something to be printed either 1/0 or true/false
Why does boolean get converted to number inside blade files but not controllers? How can I get something printed when isDesktop returns false? Right now it prints nothing in that case.
There are few methods you can achieve your requirement.
Here are couple of them,
1. Use Ternary operator like below,
{{ Setting::isDesktop() ? 'true' : 'false' }}
2. Use var_export as shown below,
{{ var_export(Setting::isDesktop()) }}

How to lookup the current context in Nunjucks?

In Handlebars you can use this to look up the current context.
How do you do the same in Nunjucks?
For example, if you wanted to dump the entire context as a JSON string:
<script>window.__config__ = {{ this | dump | safe }};</script>
(But this doesn't seem to work in Nunjucks.)
If you need context then you can add global function
var env = nunjucks.configure([...
...
env.addGlobal('getContext', function() {
return this.ctx;
})
And dump her result in template
{{ getContext() | dump| safe }}
I don't think you the variable this is available on a nunjucks template, but if it's another you wish to inspect you can use the dump method.
{{ users | dump }}
So that will print the json object, which looks really ugly if you have autoscape on.
{{ users | dump | safe }}
this will work just fine
ALTERNATIVELY:
env.addFilter('pprint', function(str, count) {
return JSON.stringify(str, null, 4);
});
{{ users | pprint | safe }}

Show default content in a template if an object is nil otherwise show based on the set property

In my template, I would like to include some default meta tags (90% of the time). However, when a specific property is set, I would like to show a different set of text.
I know I can set an anonymous struct and set a property with either "default" or "some-x". However, this means, I need to add an anonymous struct to 90% of my handlers that just currently pass nil.
Is there way to do something like
{{if eq . nil}}
// default meta tag
{{else if eq .MetaValue "some-x"}}
//other
{{end}}
If I try something like my above code, it compiles but doesn't do what I want. Appreciate any suggestions on how to handle it properly without adding a lot of boiler plate.
Thanks!
{{if not .}}
output when . is nil or otherwise empty including
false, 0, and any array, slice, map, or string of length zero
{{else if eq .MetaValue "some-x"}}
// some-x case
{{else}}
// other case
{{end}}
If you want to ensure you're only checking against nil and not 0, false, the empty string, or any other falsey type, you can use the kindIs function to accomplish this.
{{ if kindIs "invalid" . }}
// only if variable is literally nil. falsey values will fallthrough.
{{ else if eq .MetaValue "some-x" }}
// other
{{ else }}
// final case, if any
{{ end }}
I've been recently facing an issue with identifying nil vs 0 values in a Helm Chart (which uses Go templates, including sprig) and haven't found any solutions posted, so I thought I'd add mine here.
I came up with a kind of ugly solution which is to quote the value and then check for a string that matches "<nil>" (with quotes, so you'd actually be checking (quote .Values.thing | eq "\"<nil>\"")). This allows differentiating tests against empty values vs defined 0 values. In my case, I was trying to build a config file where some default options were non-0, so when 0 was explicitly set, I wanted to know that 0 was set instead of just omitted.
Hopefully this can be a help to someone else.
It would be nice to have a better way to do this, but so far I haven't found anything that doesn't require creating and adding my own template functions.

Resources