乐闻世界logo
搜索文章和话题

How to access localStorage from ejs template

1个答案

1

Server-side rendering (e.g., with the EJS template engine) typically occurs on the server. However, localStorage is a Web API exclusive to the browser environment, used for storing data on the user's browser. As the server-side lacks the capability to access the browser's localStorage, direct access from EJS templates is not feasible.

However, you can embed client-side JavaScript code within EJS templates. This code executes after the template is sent to the client and parsed by the browser. Within this client-side code, you can access localStorage normally. Below is an example of how to use localStorage in client-side JavaScript:

html
<!DOCTYPE html> <html> <head> <title>LocalStorage Example</title> </head> <body> <h1>Welcome to our website</h1> <script type="text/javascript"> // Check if localStorage is available if (typeof(Storage) !== "undefined") { // Attempt to retrieve data from localStorage var data = localStorage.getItem('someKey'); if (data) { console.log('Data retrieved from localStorage:', data); // This can be used for various purposes, such as displaying on the page // document.getElementById('someElement').textContent = data; } else { console.log('No data in localStorage for key "someKey"'); } } else { console.log('Sorry, your browser does not support Web Storage...'); } </script> </body> </html>

In the above example, when the EJS template is rendered on the server-side and sent to the client browser, the JavaScript code checks browser support for localStorage and attempts to retrieve data associated with the key 'someKey'. If data is found, it logs it to the console; otherwise, it prints a message indicating no data was found.

If you need to share data between the server-side and client-side, the common approach is to embed data into the template during server-side rendering and then save it to localStorage via client-side JavaScript. This allows the data to be utilized further on the client-side, rather than attempting direct access to localStorage on the server-side.

For example, in an EJS template, you can insert data like this:

ejs
<script type="text/javascript"> // Assume we receive a variable `serverData` from the server-side var serverData = <%- JSON.stringify(serverData) % >; // Store to localStorage localStorage.setItem('serverData', serverData); </script>

In the above EJS code snippet, serverData is a variable passed from the server-side to the template. During rendering, this data is converted to a JSON string, and the client-side JavaScript executes when the page loads, saving the data to localStorage for future use.

2024年6月29日 12:07 回复

你的答案