Skip to content

Instantly share code, notes, and snippets.

@viT-1
Created December 22, 2023 10:35
Show Gist options
  • Save viT-1/f97aa3e138bd382380bb8f019c3a2d93 to your computer and use it in GitHub Desktop.
Save viT-1/f97aa3e138bd382380bb8f019c3a2d93 to your computer and use it in GitHub Desktop.
#gist-bookmark #js #i18n #vue
@viT-1
Copy link
Author

viT-1 commented Feb 7, 2024

Tiny Mustache template renderer:

const json = {
	template: 'by formula: {{formula}}',
	formula: 'SP+{{gamma}}*25',
	gamma: '({{delta}}+4)',
	delta: 2,
};

function render (tmpl, obj) {
	const regex = new RegExp('{{([^}]+)}}', 'g');
	var rendered;
	
	const regReplacerFn = function (match, prop) {
		var retVal = obj[prop];

		if (typeof retVal !== 'string' ||
			typeof retVal === 'string' && retVal.indexOf('{{') == -1) {
			return retVal;
		}
		
		return retVal.replace(regex, regReplacerFn);
	};
	
	rendered = tmpl.replace(regex, regReplacerFn);
	
	return rendered;
}

console.log(render(json.template, json));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment