[JavaScript]Dynamic Embedding of Multiline Text and Expressions with Template Literals

目次

Overview

Using JavaScript Template Literals (introduced in ES6) allows you to intuitively and concisely create HTML code with newlines and embed calculation results directly within strings. Compared to the traditional concatenation using the plus operator (+), readability is dramatically improved. This is the standard method for generating dynamic content in DOM manipulation.


Specifications (Input/Output)

  • Input: Current date (Date object) and constant values.
  • Output: Renders HTML elements containing the date and calculation results on the screen.
  • Operation: * Retrieves today’s date when the script runs.
    • Generates an HTML string including newlines using backticks (`).
    • Performs calculations for date and values directly within the string.

Basic Usage

Instead of single quotes (') or double quotes ("), wrap the string in backticks (`). Variables are embedded using ${variable}, and newlines can be written directly.

const item = "Apple";
const price = 1.50;
const count = 3;

// Template Literals (Recommended)
// Newlines and calculations can be written as they are
const message = `
Product Name: ${item}
Total Amount: $${price * count}
`;

console.log(message);
/* Output:
Product Name: Apple
Total Amount: $4.5
*/

Full Code (HTML / JavaScript)

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Template Literals Demo</title>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        .dashboard-card {
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 20px;
            max-width: 400px;
            background-color: #f9f9f9;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        h2 { margin-top: 0; color: #333; }
        .info-text { color: #555; line-height: 1.6; }
        .highlight { color: #d32f2f; font-weight: bold; }
    </style>
</head>
<body>

    <div id="appContainer"></div>

    <script src="app.js"></script>
</body>
</html>

JavaScript

/**
 * Get the container to render the HTML
 */
const appContainer = document.querySelector('#appContainer');

/**
 * Generate and display dynamic HTML content from the current date
 */
const renderDashboard = () => {
    const today = new Date();
    const city = "Tokyo";
    const baseTemperature = 20;
    const fluctuation = 4; // Variable value

    // Generate HTML using Template Literals
    // 1. Backticks allow writing newlines directly
    // 2. Calculations like (baseTemperature + fluctuation) can be executed inside ${}
    // 3. Method calls like (today.getMonth() + 1) are also possible
    const htmlContent = `
        <div class="dashboard-card">
            <h2>
                📅 ${today.getFullYear()}/${today.getMonth() + 1}/${today.getDate()} Weather
            </h2>
            <div class="info-text">
                <p>Area: <strong>${city}</strong></p>
                <p>
                    The forecast high is 
                    <span class="highlight">
                        ${baseTemperature + fluctuation}℃
                    </span>.
                </p>
                <p>Message:<br>Let's do our best today!</p>
            </div>
        </div>
    `;

    // Insert the generated HTML string into the DOM
    appContainer.innerHTML = htmlContent;
};

// Execute
renderDashboard();

Customization Tips

  • Function Embedding: You can also execute functions inside ${}. By calling a function that changes content based on conditions and embedding its return value, you can flexibly link logic and view.
const getStatus = (score) => score > 80 ? "Pass" : "Fail";
const text = `The result is ${getStatus(90)}`;
  • Using Ternary Operators: While if statements cannot be used inside template literals, ternary operators (condition ? true : false) are available.
const className = `btn ${isActive ? 'btn-primary' : 'btn-secondary'}`;

Important Notes

  • XSS (Cross-Site Scripting) Vulnerability: When assigning strings generated by template literals to innerHTML, it is dangerous to embed user input directly, as it could include malicious scripts. Always sanitize user input or use textContent instead.
  • Backtick Input: On Japanese JIS keyboards, the backtick ` is entered with Shift + @. Be careful not to confuse it with the single quote '.
  • IE Incompatibility: Internet Explorer 11 (IE11) does not support template literals. If you need to support legacy browsers, you must use a transpiler like Babel or stick to traditional string concatenation.

Advanced Applications

Tagged Template Literals

This is an advanced feature where a function name is written immediately before a template literal to customize the string parsing. It is often used for escaping.

// Function that receives string parts and variable parts separately
const sanitize = (strings, ...values) => {
    // Implementation for escaping values could go here
    return strings[0] + values[0] + strings[1]; 
};

const input = '<script>alert("xss")</script>';
// Processed through the sanitize function
const safeHtml = sanitize`The input value is ${input}`;

Summary

The introduction of template literals has made building HTML and generating messages in JavaScript much easier.

  • Multiline text can be written directly without \n.
  • Variables and expressions are cleanly embedded with ${}. Utilize these techniques to keep your code readable, especially when creating HTML strings.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次