0

I'd like to access a value that exists on the object where a tagged template literal is located, without introducing extra syntax.

function myTemplate(str: TemplateStringsArray) {
  console.log(this.myValue)
  return str[0] 
}

function Create(options) {
  return options
}

const value = Create({
  myValue: 'something',
  template: myTemplate`
    some text
  `
})

I would like the console.log(this.myValue) to print the value located on the object it's nested within.

The following works, but I don't want to have to bind the template like this.

const value = Create({
  myValue: 'something',
  template: myTemplate.bind(this)`
    some text
  `
})

I tried binding it in the Create function like so:

function Create(options) {
  options.template.bind(options)
  return options
}

But of course, it doesn't work as the tag has already been evaluated.

David Alsh
  • 6,747
  • 6
  • 34
  • 60

1 Answers1

1

Got it. I had to return a function from the template literal and pass in the options from the create function

function myTemplate(str: TemplateStringsArray) {
  return function(options: any) {
    console.log(options.myValue)
    return str[0] 
  }
}

function Create(options: any) {
  options.template = options.template(options)
  return options
}

const value = Create({
  myValue: 'something',
  template: myTemplate`
    some text
  `
})
David Alsh
  • 6,747
  • 6
  • 34
  • 60