String
Template
Post
String Template Expression
A String template expression constructs a string value using the Template expression.
✍ Syntax
String Template
string ` BacktickItem* Dollar* `
Here
- BacktickItem := BacktickSafeChar| BacktickDollarsSafeChar| Dollar* interpolation
- interpolation :=
${expression} - BacktickSafeChar := ^ (
`|$) - BacktickDollarsSafeChar :=
$+ ^ ({|`|$) - Dollar :=
$
✍ Syntax
String Template syntax support interpolation (Syntax ${expr}) and each interpolation expression must have a type that is a subtype of boolean|int|float|decimal|string. You can use this expression in places where you use string concatenation, or you need to build multi-line string values.
| |
bal run string_template.balHello, Bob!
Your id is 2
Your department is IT
Your salary is 45000
bal versionBallerina 2201.6.0 (Swan Lake Update 6)
// Partial Code. Change View to see full code.
type Employee record {
int id;
string name;
decimal salary;
};
public function main() {
Employee emp = {name: "Bob", id: 2, salary: 45000};
string department = "IT";
string s1 = string `Hello, ${emp.name}!`;
string s2 = string `Your id is ${emp.id}
Your department is ${department}
Your salary is ${emp.salary}`;
}String Template Expression Example
How String Interpolation works
- Step 1 - Take every character that is not part of the interpolation within the two
`Backtick, including newline, CR, etc. These characters are sliced based on interpolation expression positions. - Step 2- Evaluate each interpolation expression in the order in which they were written. Then Take the string representation of the values, by using the
value:toString()lang-lib function. - Step 3 - Construct the final string value interleaving Step 1 and Step 2 results.
Special Cases
🚫 No Escape Characters
Unlike string-literal, String Template doesn’t support escape characters.
✅Use interpolation to handle special cases
Use string-literal with interpolation to type such characters i.e. ${"`"}.
| |
bal run template_special.bal\\ \n \t
backtick - `
Price $100
Some long text, but you need to break the source code into multiple lines without affecting the string value.
bal versionBallerina 2201.6.0 (Swan Lake Update 6)
// Partial Code. Change View to see full code.
public function main() {
string s1 = string `\\ \n \t`;
string s2 = string `backtick - ${"`"}`;
int value = 100;
string s3 = string `Price $${value}`;
string s4 = string `Some long text, but you need to break the source code ${""
} into multiple lines without affecting the string value.`;
}String Template Special Cases
Code Breakdown
- Line 4: Escape characters are not supported in String Template.
- Line 5: Use interpolation to type such characters like backtick character i.e.
${"`"}. - Line 8: Additional
$character doesn’t have any special meaning in String Template. - Line 10-11: You can break the source code into multiple lines without affecting the string value, by using an empty string interpolation expression.