JessePinkman
JessePinkman

Reputation: 651

Dart: How to force string interpolation on a variable

I have a variable that contains a string with interpolated variables. In the code below, that variable is template. When I pass this variable to generateString function, I want to apply string interpolation on it because the values which interpolated variables require are available in generateString function only.

void main() {
  String template = '<p>\${name}</p>';
  var res = generateString(template);
}

generateString(template) {
  var name = 'abc';
  print(template);
  return template;
}

The problem is when I am printing and returning template inside generateString fn, I am getting <p>${name}</p> instead of <p>abc</p>. Is there a way to explicitly tell the dart to so string interpolation?

I am new to Dart. I don't know if it is even possible to achieve or not. Please suggest how do I do this.

Edit: Based on the inputs from other users, I would like to make a clarification about the scenario presented. The value of template variable is not a string literal. I get that from UI as a user input. I have shown it here as a string literal for code simplicity. Also, please consider that name and template are not in the same scope in my scenario.

Upvotes: 6

Views: 16072

Answers (4)

Randal Schwartz
Randal Schwartz

Reputation: 44091

The other answers so far are wrong.

String interpolation (looking for $, etc) happens only while compiling from the source code to the value in memory. If that string in turn also has a $, it's no longer special.

It's not possible to trigger interpolation past the original compilation step. You can write a templating system that would look for something like {{name}} in the value, and replace it with the current value of name.

Upvotes: 7

encubos
encubos

Reputation: 3303

If you have the template and the variable in the same scope, it works as expected.

// evaluate variable inside ${}
var sport = 'basketball';
String template = 'I like <p>${sport}</p>';
print(template);

Upvotes: 3

Mr Random
Mr Random

Reputation: 2218

I didn't fully understand your question maybe this will help

void main() {
  print(generateString('abc')); //<p>abc</p>
}

generateString(String template) {
  return r"<p>" "$template" r"</p>";
}

Upvotes: 1

Teddichiiwa
Teddichiiwa

Reputation: 791

Walter White here.

You must define the variable name as global var, so it can "cook" the string for you

Upvotes: -1

Related Questions