jadjoubran / codetogo.io

🚀 JavaScript code to go - Find updated snippets for common JavaScript use cases
https://codetogo.io
MIT License
231 stars 30 forks source link

Use Case Suggestion: dynamic template #198

Closed Jefftopia closed 5 years ago

Jefftopia commented 5 years ago
    const interpolate = (template, data) => {
        return new Function(`return \`${template}\`;`).call(data);
    }

    let myTemplate = "Hello ${this.world}!";
    let data = { world: 'world' };
    let result = interpolate(myTemplate, data); 
    console.log(result); // "Hello world!"
jadjoubran commented 5 years ago

Thanks @Jefftopia Is there a reason why you wouldn't use template strings here? especially that they could be tagged with a method, for example:

const html = (template, ...args) => {
    console.log(template, args);
}

html`this is a dynamic template ${1 +1}`
Jefftopia commented 5 years ago

@jadjoubran Tagged templates are transformations of templates, but they're still template literals.

For dynamic, consider the case where a user fetches a string from a headless CMS. In that case, the value returned by a JSON API will be { foo: "${bar}, how are you?" }. A literal template doesn't solve this case.

jadjoubran commented 5 years ago

Thanks @Jefftopia that makes sense, however it's very specific to this use case, whereas codetogo is aimed towards Beginner to Intermediate developers So when they see this usecase they might think it's a good idea to use it anytime Thus I'd prefer to only accept use cases that are generic enough to be used by anyone! Thanks again for your suggestion!