Skip to content

Document tagged templates #803

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions data/sidebar_manual_latest.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"lazy-values",
"promise",
"async-await",
"tagged-templates",
"module",
"import-export",
"attribute",
Expand Down
36 changes: 36 additions & 0 deletions misc_docs/syntax/decorator_taggedTemplate.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
id: "taggedTemplate-decorator"
keywords: ["taggedTemplate", "tagged", "template", "decorator"]
name: "@taggedTemplate"
summary: "This is the `@taggedTemplate` decorator."
category: "decorators"
---
**Since 11.1**

The `@taggedTemplate` decorator is used to bind to JavaScript tag functions.

### Example

<CodeTab labels={["ReScript", "JS Output"]}>

```res example
// see https://bun.sh/docs/runtime/shell
type result = {exitCode: int}
@module("bun") @taggedTemplate
external sh: (array<string>, array<string>) => promise<result> = "$"

let filename = "index.res"
let result = await sh`ls ${filename}`
```

```js
import * as $$Bun from "bun";
var filename = "index.res";
var result = await $$Bun.$`ls ${filename}`;
```

</CodeTab>

### References

* [Tagged template functions](/docs/manual/latest/bind-to-js-function#tagged_template-functions)
27 changes: 19 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
"gentype": "^3.44.0",
"glob": "^7.1.4",
"gray-matter": "^4.0.3",
"highlight.js": "^10.5.0",
"highlight.js": "^11.9.0",
"highlightjs-rescript": "^0.1.2",
"lz-string": "^1.4.4",
"next": "^13.1.1",
"next-mdx-remote": "^4.4.1",
Expand All @@ -42,8 +43,8 @@
"remark-parse": "^10.0.2",
"remark-slug": "^5.1.2",
"remark-stringify": "^7.0.3",
"rescript": "^11.0.0",
"request": "^2.88.0",
"rescript": "^11.0.0",
"stringify-object": "^3.3.0",
"unified": "^8.4.0"
},
Expand Down
36 changes: 36 additions & 0 deletions pages/docs/manual/latest/bind-to-js-function.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -421,3 +421,39 @@ Currently 4 directives are supported: `null_to_opt`, `undefined_to_opt`, `nullab
<!-- When the return type is unit: the compiler will append its return value with an OCaml unit literal to make sure it does return unit. Its main purpose is to make the user consume FFI in idiomatic OCaml code, the cost is very very small and the compiler will do smart optimizations to remove it when the returned value is not used (mostly likely). -->

`identity` will make sure that compiler will do nothing about the returned value. It is rarely used, but introduced here for debugging purpose.

## Tagged template functions

**Since 11.1**

**Experimental** You can easily bind to [JS tagged template functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates).
Tag functions in JS expect as input an array of strings and variadic parameters for the arguments of the interpolation.
To bind to those functions in rescript, the binding signature must have two arrays as arguments,
the first one being an array of strings and the second can be an array of anything.
You add the `@taggedTemplate` annotation and you're good to go!

<CodeTab labels={["ReScript", "JS Output"]}>

```res example
// see https://bun.sh/docs/runtime/shell
type result = {exitCode: int}
@module("bun") @taggedTemplate
external sh: (array<string>, array<string>) => promise<result> = "$"

let filename = "index.res"
let result = await sh`ls ${filename}`
```

```js
import * as $$Bun from "bun";
var filename = "index.res";
var result = await $$Bun.$`ls ${filename}`;
```

</CodeTab>

Notice that it gets compiled to tagged template literals in JS, which allows
to use JS tools that only work on the literals and not by calling directly the tag function.

There are plenty of useful JS tools you can bind to, like [`gql`](https://github.com/apollographql/graphql-tag),
[`sql`](https://github.com/porsager/postgres), [`css`](https://github.com/mayank99/ecsstatic) and a lot others!
23 changes: 23 additions & 0 deletions pages/docs/manual/latest/interop-cheatsheet.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ This is a glossary with examples. All the features are described by later pages.
- [`@uncurry`](bind-to-js-function#extra-solution)
- [`@unwrap`](bind-to-js-function#trick-2-polymorphic-variant--bsunwrap)
- [`@val`](bind-to-global-js-values#global-modules)
- [`@taggedTemplate`](bind-to-js-function#tagged_template-functions)

- [`@deprecated`](attribute#usage)
- [`genType`](https://github.com/reason-association/genType)
Expand Down Expand Up @@ -193,6 +194,28 @@ external join: array<string> => string = "join"

</CodeTab>

### Tagged template functions

<CodeTab labels={["ReScript", "JS Output"]}>

```res example
// see https://bun.sh/docs/runtime/shell
type result = {exitCode: int}
@module("bun") @taggedTemplate
external sh: (array<string>, array<string>) => promise<result> = "$"

let filename = "index.res"
let result = await sh`ls ${filename}`
```

```js
import * as $$Bun from "bun";
var filename = "index.res";
var result = await $$Bun.$`ls ${filename}`;
```

</CodeTab>

### Polymorphic Function

<CodeTab labels={["ReScript", "JS Output"]}>
Expand Down
13 changes: 7 additions & 6 deletions pages/docs/manual/latest/overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,13 @@ canonical: "/docs/manual/latest/overview"

### String & Character

| JavaScript | ReScript |
| --------------------------| --------------------- |
| `"Hello world!"` | Same |
| `'Hello world!'` | Strings must use `"` |
| `"hello " + "world"` | `"hello " ++ "world"` |
| `` `hello ${message}` `` | Same |
| JavaScript | ReScript |
| ----------------------------- | --------------------- |
| `"Hello world!"` | Same |
| `'Hello world!'` | Strings must use `"` |
| `"hello " + "world"` | `"hello " ++ "world"` |
| `` `hello ${message}` `` | Same |
| `` sql`select ${fnName};` `` | Same |

### Boolean

Expand Down
124 changes: 124 additions & 0 deletions pages/docs/manual/latest/tagged-templates.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
---
title: "Tagged templates"
description: "Using tagged templates in ReScript"
canonical: "/docs/manual/latest/tagged-templates"
---

# Tagged templates

**Since 11.1**

Tagged templates provide a special form of string interpolation, enabling the creation of template literals
where placeholders aren't restricted to strings. Moreover, the resulting output isn't confined solely to
strings either. You can take a look at the [JS documentation
about tagged templates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)
to learn more about them.

## Define a tag function

Tag functions in ReScript have the following signature:
```res
let myTagFunction : (array<string>, array<'param>) => 'output
```
As you can see, you can have any type you want both for the placeholder array and for the output.

Given how string interpolation works, you'll always have the following invariant:
```res
Array.length(strings) == Array.length(placeholder) + 1
```

Let's say you want to interpolate strings with all kind of builtin types and make it work inside React components,
you can define the following tag function:

<CodeTab labels={["ReScript", "JS Output"]}>

```res prelude
type params =
| I(int)
| F(float)
| S(string)
| Bool(bool)

let s = (strings, parameters) => {
let text = Array.reduceWithIndex(parameters, Array.getUnsafe(strings, 0), (
acc,
param,
i,
) => {
let s = Array.getUnsafe(strings, i + 1)
let p = switch param {
| I(i) => Int.toString(i)
| F(f) => Float.toString(f)
| S(s) => s
| Bool(true) => "true"
| Bool(false) => "false"
}
acc ++ p ++ s
})
React.string(text)
}
```
```js
import * as Core__Array from "./stdlib/core__Array.js";

function s(strings, parameters) {
return Core__Array.reduceWithIndex(parameters, strings[0], (function (acc, param, i) {
var s = strings[i + 1 | 0];
var p;
switch (param.TAG) {
case "I" :
case "F" :
p = param._0.toString();
break;
case "S" :
p = param._0;
break;
case "Bool" :
p = param._0 ? "true" : "false";
break;

}
return acc + p + s;
}));
}
```

</CodeTab>

## Write tagged template literals

Now that you have defined your tag function, you can use it this way:

<CodeTab labels={["ReScript", "JS Output"]}>

```res example
module Greetings = {
@react.component
let make = (~name, ~age) => {
<div> {s`hello ${S(name)} you're ${I(age)} year old!`} </div>
}
}
```
```js
function Greetings(props) {
return React.createElement("div", undefined, s([
"hello ",
" you're ",
" year old!"
], [
{
TAG: "S",
_0: props.name
},
{
TAG: "I",
_0: props.age
}
]));
}
```

</CodeTab>

Pretty neat, isn't it? As you can see, it looks like any regular template literal but it accepts placeholders that are not strings
and it outputs something that is not a string either, a `React.element` in this case.
Loading