string-template
string-template copied to clipboard
Ignore slots without value provided
First of all, thank you for your lib :)
I'm experiencing a possible bug. If I try this example:
const replaceTemplate = require('string-template');
const input = "https://{user}:{password}@{domain}/api/endpoint1?parameter1={parameterValue1}";
const replacements = {
user: 'Eric',
password: 'a pass',
domain: 'any-url.com'
};
const test = replaceTemplate(input, replacements);
The result is like this:
"https://Eric:a [email protected]/api/endpoint1?parameter1=";
parameterValue1 is lost. I should expect an output like this:
"https://Eric:a [email protected]/api/endpoint1?parameter1={parameterValue1}";
To put you in context, I'm developing an API with Loopback 4 using datasource templating and they use {} as delimiters. My idea was to join their bindings with my own thanks to your lib.
Maybe it could also be related with https://github.com/Matt-Esch/string-template/issues/12 because with custom delimiters, this error could be work-arounded.
yes. it makes more sense to just substitute passed variables and skip substituting unavailable variables
current code replaces all substitution points with variables available (like user, password, domain) and unavailable (like parameterValue1) with ""
instead, it needs to iterate passed variables and then substitute them one by one. something like this:
const format = (template, vars) =>
Object.entries(vars).reduce(
(acc, [key, val]) => acc.replace(`{${key}}`, val),
template
)
@Matt-Esch let me know if it makes sense to you too. i'll happily make a PR
I think the code could be modified to do this but it would be a breaking change if not flagged. The module was designed for use where the named values are supplied every time and this was a performance tradeoff.
I will also mention that your example is dangerous and not a good use case for string template as these values need to be escaped properly to form a valid URL, otherwise it is subject to url rewriting though setting a malicious user variable.