sindresorhus / pupa

Simple micro templating

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Escape dot character

nghieptiki opened this issue · comments

Hi guys,
Sometimes, my data is an object that includes a dot character.

pupa('The mobile number of {name} is {phone\.mobile}', {
    name: 'Sindre',
    "phone.mobile": "609 24 363"
});

Maybe should be supported \ character to escape the dot character.

Sure. That could be supported.

JS simply ignores \ in \. and returns the string as . only. So, should the escape character be \\?

I did some tests considering \\ as the escape character

Changed the regexes in the following lines

pupa/index.js

Line 41 in c9eb134

const doubleBraceRegex = /{{(\d+|[a-z$_][\w$]*?(?:\.[\w$]*?)*?)}}/gi;

pupa/index.js

Line 47 in c9eb134

const braceRegex = /{(\d+|[a-z$_][\w$]*?(?:\.[\w$]*?)*?)}/gi;

to

- {{(\d+|[a-z$_][\w$]*?(?:\.[\w$]*?)*?)}}
+ {{(\d+|[a-z$_][\w$]*?(?:\\?\.[\w$]*?)*?)}}

Replaced

pupa/index.js

Lines 22 to 24 in c9eb134

for (const property of key.split('.')) {
value = value ? value[property] : undefined;
}

with

for (const property of key.split(/(?<!\\)\./gi)) {
  const normalizedProp = property.replace('\\', '');
  value = value ? value[normalizedProp] : undefined;
}

The replace('\\', '') is just to get rid of the extra \ in the template

Then added the following tests,

t.is(pupa('The mobile number of {name} is {phone\\.mobile}', {
	name: 'Sindre',
	'phone.mobile': '609 24 363',
}), 'The mobile number of Sindre is 609 24 363');
t.is(pupa('The mobile number of {name} is {{phone\\.mobile}}', {
	name: 'Sindre',
	'phone.mobile': '<b>609 24 363</b>',
}), 'The mobile number of Sindre is &lt;b&gt;609 24 363&lt;/b&gt;');

All the tests seem to be passing. If this looks good then I can create a PR

I think the best solution for this is to use a proper parser. #25 can be used as starting point for anyone wanting to work on this.

commented

Would it be better to use dot-prop for getting values instead? The escapePath function would work for this.