0

Context: I am trying to create a template builder for emails and I have noticed that I can't update the theme colours as JavaScript passes the values into the object.

I have two object's, theme and templates.

// Theme settings
const theme = [
  {
    primary: '#0074ff',
    secondary: '#222222',
    text: '#111111',
    fontSize: '14px',
    fontFamily: 'Helvetica Neue, Helvetica, Arial, sans-serif',
    background: '#e0e2e3',
    container: '#ffffff',
    padding: '16px 16px',
  }
];

// Templates
const emailTemplates = [
  {
    title: 'Template 1',
    fields: [ 
        { id: 'image', name: 'Image URL', type: 'text', default: 'https://via.placeholder.com/200x80' },
        { id: 'imageWidth', name: 'Image width (pixels)', type: 'number', default: '200' } 
    ],
    code: `<div style="padding: ${theme[0].padding}"><img src="{{image}}" width="{{imageWidth}}"/></div>`
  },
  {
    title: 'Template 2',
    fields: [ 
        { id: 'text', name: 'Body text', type: 'text', default: 'Lorem ipsum' }
    ],
    code: `<p style="color: ${theme[0].text}">{{text}}</p>`
  },
  // Other templates
]

Note: don't worry about the use of inline styles as this is designed for HTML emails which for compatibility reasons requires inline styling.

What have I tried: I have tried to do the solution in this StackOverflow . But it doesn't seem to add the values in either.

When I console.log the emailTemplates object, the values for the theme variables appear to be hard coded in the code property. How can I make it so that it is able to be updated.

For example: If I update the theme variables, I'd like the values in the emailTemplates to also update.

console.log(theme[0].text); // returns '#111111'
console.log(emailTemplates[1].code); // returns '<p style="color: #111111">{{text}}</p>'

// If I change the value for the theme, I want the emailTemplates value to also update
theme[0].text = '#222222';
console.log(theme[0].text); // returns '#222222'
console.log(emailTemplates[1].code); // returns '<p style="color: #111111">{{text}}</p>'

Please let me know if something like this is possible.

Lachie
  • 1,321
  • 1
  • 10
  • 26
  • As you say, when you do ```something = `blah ${x}`;```, the *value* of `x` is read when the template literal is evaluated and a string is created (since it's an untagged template literal). To defer it, wrap it in a function or use a tag function on it. – T.J. Crowder Mar 22 '23 at 08:14

0 Answers0