How to create a tagged template literal and pass argument to another tagged template literal?

1k Views Asked by At

Let's say I have

const highlight = (strings, ...values) => {
 // console.logs in highlight
}

Let's say I want to create a "middleware" that modifies the template and then call highlight instead:

const doMore = (string, ...values) => {
 // modify string/values and then call highlight here
}

So that I can now do something like

doMore`
the string ${template}
`;

I cannot figure out how to call highlight from doMore. How do I do this?

My first attempt was to use the ... operator. But this did not work. Specifically, I'm trying to create a wrapper for the npm chalk application, so I did something like:

const doMore = (string, ...values) => {
 // extend string, values
 return chalk(string, ...values)
}

but this throws an error: chalk_1.default.apply is not a function. Normally doing

chalk`the string ${template}`

but calling it using the spread operator is throwing this error.

2

There are 2 best solutions below

1
Aplet123 On

You can use the ... spread syntax to convert an array into a list of arguments to call highlight:

const doMore = (string, ...values) => {
    string += " foo";
    values = values.map(v => v + " bar");
    return highlight(string, ...values);
};
0
Ramil Amparo On

It looks like chalk_1.default.apply is an error from the transpiler that you are using rather than your code.

Here is an example of modifying the output from the tagged template literal.

const doMore = (template, ...values) => {
    /**
     * Make sure the template array is the same length as template.raw
     */
    /** Add START on the first line. */
    template[0] = "START" + template[0];
    template.raw[0] = "START" + template.raw[0];
    /** Add END on the last line. */
    template[template.length - 1] =
        template[template.length - 1] + "\nEND";
    template.raw[template.raw.length - 1] =
        template.raw[template.raw.length - 1] + "\\nEND";
    return chalk(template, values);
};
console.log(doMore`
{red This text is shown in red.}
${"This text is inserted."}
{green This text is shown in green.}`);

Outputs:

START
This text is shown in red.
This text is inserted.
This text is shown in green.
END