Is there any PPX for template strings in OCaml?

I’m very new to OCaml, and coming from other languages, I’m wondering if there’s some PPX which gives you efficient template strings. For example,

let name = "aria" in [%str{|Hello {name}|}]

would end up as “Hello aria”. Where the output from the PPX would be use Buffers to add the strings together (since I’ve heard that it’s better to do that than use ^)

let name = "aria" in
let buf = Buffer.create 20 in
Buffer.add_string buf "Hello";
Buffer.add_string buf name;
buf |> Buffer.to_bytes |> Bytes.to_string

Does something like this already exist? If it doesn’t exist, would you have any advice if I wanted to try and make it myself?

In you code, you should replace Hello with “Valar morgulis”. :wink:

Are you looking to generate HTML in the end?
I guess there are several OCaml libraries for this context.

1 Like

I’m not trying to generate HTML no. Honestly I just want to learn more about PPX either by reading the code of a library that already does what I want or by doing it myself…in which case I’d need a little help.

It’s not a PPX but I would take a look at https://github.com/rgrinberg/ocaml-mustache. Long strings in OCaml are supported by {|…|} syntax.

There’s this ppx called ppx_string_interpolate which does exactly what you describe.

Unfortunately it looks a bit old, would be good to revive it!

2 Likes

Wow that’s exactly what I wanted to do. I searched for this for a while, and couldn’t find it so thanks a lot!

It wold be a good candidate for ocaml-community I think. Maybe I’ll ask the author.

4 Likes

Yeah, would be very nice is this was part of opam packages. :confused:

Please feel free to use this if it fits your needs:

2 Likes

There’s also Jane Street’s ppx_string.