How to format strings and hexadecimals in Scriban

669 views Asked by At

I am writing C# solution that generates a C++ file base on some configuration. For this i am using Scriban as a template engine. I saw the following statement before in Jinja2:

uint16_t {{"%25s"|format(device.name)}} = {{"0x%08x"|format(device.address)}};

device.name is a string and device.address contain Hexadecimal value (0x50060800).

I tried this:

uint16_t {{device.name | object.format "%25s"}} = {{device.address | math.format "0x%08x"}};

And i received the following error:

<input>(15,50) : error : Unexpected `RNG`. Must be a formattable object
<input>(15,71) : error : Unexpected `0x50060800`. Must be a formattable object

This is the result I was expecting:

uint16_t RNG = 0x50060800;

How can I implement the above statement in Scriban?

1

There are 1 answers

1
Mike Christiansen On BEST ANSWER

I answered in your GitHub issue. I'll paste here for posterity

Keep in mind:

  • Jinja is written for Python. So, it uses Python conventions for things like format strings.
  • Scriban is written in C# - it uses C# conventions for format strings.

Based on this StackOverflow post, it seems that by using "%25s", you are attempting to pad the width of device.name to 25 characters. The way to do that in Scriban is using the string.pad_right (or string.pad_left) function.

Additionally, your hex format string is incorrect (see the C# documentation on the X specifier for numeric format strings)

Putting all that together:

uint16_t {{device.name | string.pad_right 25 }} = 0x{{device.address | math.format "X8"}};

Note, however, the numeric format strings only work on numeric types. So, if the device.address property is a string in decimal representation (i.e., "1342572544"), you first must convert it to a number, like so:

0x{{device.address | string.to_int | math.format "X8"}};

If the device.address property is a string in hexadecimal representation, it gets a bit tricker. I don't see a built-in function to convert that for you. So, you'll have to make your own. See an example here