Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting variable name passed in tagged templating

I'm wondering if there is a simple way to retrieve the name of the variables inside a tagged Template function. To be more clear, this is the code:

let date = "2018"; //can be undefined
let description = "my description"; //can be undefined
let age; //can be undefined, and it is here
    function processString(parts) {
        var res = parts[0];
        for (var i=1; i<parts.length; i++) {
            if (arguments[i]) res += /*** arguments[i] is the value, I want to append the variable name too***/ arguments[i];
            res += parts[i];
        }
        return res;
    }
    console.log(processString`
    ${date}
    ${description}
    ${age}
    `);

This is the result

2018
my description
20

I want this

date: 2018
description: my description
age: 20

EDIT: The whole purpose is to generate a list of "optional" rows (the original code is more complex of course, actually it generates a SQL-like query), but if the variable arguments[i] is defined I want to append to the resulting string "variable_name: variable_value" please note I edited the function processString. If there is any solution, I would prefer to edit processString and keep clean the console.log

like image 300
alfredopacino Avatar asked Apr 20 '26 06:04

alfredopacino


1 Answers

To extend on Angelas' answer, you could pass in an object literal, as:

{name}

is the same as

{"name" : name}

So you can access both the name and the values. The template would look like:

function template(str, ...args) {
  let result = "";
  for(var i = 0; i < str.length - 1; i++) {
    result += str[i];
    result += Object.entries(args[i])[0].join(" : ");
  }
  result += str[i];
  return result;
}

So that you can do:

template`
  1 - ${{date}}
  2 - ${{description}}
`;
like image 180
Jonas Wilms Avatar answered Apr 21 '26 19:04

Jonas Wilms