Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use string interpolation in a resource file?

I would like to use a resource file to send an email. In my resource file I used a variable "EmailConfirmation" with the value "Hello {userName} ... "

In my class I used:

public static string message (string userName)
{
   return Resource.WebResource.EmailConfirmation
}

The problem is that the return says "Hello {userName}" instead of "Hello Toto".

like image 546
Jahack Avatar asked Feb 17 '18 19:02

Jahack


People also ask

How do you do interpolation strings?

Structure of an interpolated string. To identify a string literal as an interpolated string, prepend it with the $ symbol. You can't have any white space between the $ and the " that starts a string literal. To concatenate multiple interpolated strings, add the $ special character to each string literal.

How do you do string interpolation in JavaScript?

You can add values into a JavaScript string using a template literal. This is a dollar sign followed by a pair of curly brackets. Within the curly brackets should be the expression whose value you want to embed in the string.

Why do we use string interpolation?

String Interpolation is a process in which the placeholder characters are replaced with the variables (or strings in this case) which allow to dynamically or efficiently print out text output. String Interpolation makes the code more compact and avoids repetition of using variables to print the output.


1 Answers

You can't make use of string interpolation in the context of resources. However you could achieve that you want by making use of string.Format. Write to your resource file something like this:

Hello {0}

and then use it like below:

public static string message (string userName)
{
   return string.Format(Resource.WebResource.EmailConfirmation, userName);
}

Update

You can add as many parameters as you want. For instance:

Hello {0}, Confirm your email: {1}

And then you can use it as:

string.Format(Resource.WebResource.EmailConfirmation
    , userName
    , HtmlEncoder.Default.Encode(link))
like image 134
Christos Avatar answered Sep 19 '22 18:09

Christos