soasme / nim-mustache

Mustache in Nim

Home Page:https://mustache.github.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ENH: support float format

brentp opened this issue · comments

Given something like:

let ctx = newContext()
ctx["name"] = 1.234903242343234534
echo ctx["name"].castStr

I'd like to be able to specify to only output, for example 1.235. I tried this:

proc `$`*(f:float): string =
  return &"{f:.2f}"

but that didn't change the template output for me.

one option could be to have a ctx["name_raw"] which contains the float value and a ctx["name"] that contains a lambda that formats ctx["name_raw"] as a string and in the way you want it.

commented

@brentp Nim-mustache does not process $ output.

You can wrap up your float values into a customized type and control the strformat leveraging by the castValue API like below:

# File: issue_16.nim

import mustache, strformat

type HumanReadableFloat = object
  vFloat*: float

proc castValue(value: HumanReadableFloat): Value =
  Value(kind: vkString, vString: &"{value.vFloat:.2f}")

var c = newContext()
c["raw_float"] = 1.234903242343234534
c["readable_float"] = HumanReadableFloat(vFloat: 1.234903242343234534)

let s = """
{{ raw_float }}
{{ readable_float }}
"""

echo(s.render(c))

Output:

1.234903242343234
1.23
commented

Please see how to use castValue doc here.

cheers. I'll do that. thank you.