Jindrich Vavruska
Jindrich Vavruska

Reputation: 832

Is it possible to use javascript tagged template string to interpolate over an array value?

Let's assume there is an object table like this (representing a database table structure):

table = { name: "Some table", code: "SOME_TABLE", 
  columns: [
    { name : "Identifier", code: "ID", typ: "number" },
    { name : "Description", code: "DESCR", typ: "varchar2", length: 255 },
  ]
}

Is there a pattern how to write substitution function that would allow interpolation of table.columns array within a tagged template literal?

Something like

function sqlCreate ( strings, ...values ) { 
   ... do something very smart ...
}

and use it:

sqlCreate`create table ${table.code} ( ...something...${table.columns}...inner template...${'.code'} ${'.typ'}...end of inner template )`

where ${'.code'} and ${'.type'} would somehow refer to the properties of object in table.column array.

I tried to figure out but it seems it doesn't make much sense and instead there should be a specialized generator function that would do the right thing.

Are you aware of any successful attempt to solve this as a "pure template solution"?

Upvotes: 1

Views: 179

Answers (1)

artem
artem

Reputation: 51629

You need some way to delimit inner template. You can invent your own syntax for indicating where it starts and ends, or you can just use syntax that's already there - you can have inner template string inside ${}.

For something as simple as your example, you don't even need custom tag function:

`create table ${table.code} (${table.columns.map(col =>`${col.code} ${col.typ}`).join(', ')})`

Note: because ${} in template strings are always evaluated immediately, you always have to have inner template embedded in some callback function code to delay evaluation. Or you have to go the "template engine" way.

Upvotes: 1

Related Questions