@Vit632

Как передать коллекцию из ejs в функцию javascript?

Как передать коллекцию из ejs в функцию javascript или как использовать коллекцию в javascript?

Текущая логика
- из БД в view index.ejs попадает коллекция `articles`;
- в view index.ejs составляем список - <% articles.forEach((article, index) => { %>

Ожидаемая логика
- из БД в view index.ejs попадает коллекция `articles`;
- в view index.ejs составляем список - <% articles.forEach((article, index) => { %>;
- пользователь кликает по "тегу < a >" ;
- в функция JavAScript принимает параметры коллекция `articles`, `id``;
- функция JavAScript:
- - по id получает элемент коллекции article;
- - получает свойство content элемента коллекции article .
- - свойство content отображается в элементе страницы.

Конечная цель: отобразить свойство content в элементе страницы.
Я пробую это реализовать, не получаю результата.

Вопросы.
1. Правильно ли я сделал код?
2. Как сделать данное решение правильно?

Текущий код. Кратко
index.ejs. Тег - а
<a style="font-weight: bold;" href="#"><%=article.title%></a>


index.ejs
<!--  Arbitrary code ...  --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- -->
 <!-- LEFT MENU  --- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- -->
                        <div class="col-3 d-flex">
                            <aside class="bg-danger bg-gradient w-100 d-flex justify-content-left align-items-center text-dark fs-5">                                
                                <% if (articles.length > 0) { %>
                                    <ul>
                                        <% articles.forEach((article, index) => { %>
                                        <li>
                                            <input type="hidden" class="articles" name="articles[]" value="<%= article.id %>">     
                                            <span>
                                                <a style="font-weight: bold;" href="#"><%=article.title%></a>
                                            </span>    
 <!--  Arbitrary code ...  --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- -->


---
Ожидаемый код. Кратко
Тег `< a >`
<a style="font-weight: bold;" href="#" onclick="setMessage3('<%=articles%>', '<%=article.id%>')"><%=article.title%></a>

Тег < script >
<script>                
                function setMessage3(articles, id) {
			 <!--  Arbitrary code ...  --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- -->
			console.log(id);
			console.log(thisArticles[id].content);
                }
            </script>

62f8aa9cc6ab8110620956.png

Или решение-2. Сразу использовать коллекцию в JS.
Тег < script >
<script>                
             function setMessage4(id) {                    
                    let thisArticles = '<%=articles%>';  
                
                    console.log(thisArticles[id].content);
                }
            </script>

62f8aab8948f3192167719.png

Фрагмент index.ejs
<!--  Arbitrary code ...  --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- -->
<!-- LEFT MENU  --- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- -->
<div class="col-3 d-flex">
	<aside class="bg-danger bg-gradient w-100 d-flex justify-content-left align-items-center text-dark fs-5">                                
		<% if (articles.length > 0) { %>
			<ul>
				<% articles.forEach((article, index) => { %>
				<li>
					<input type="hidden" class="articles" name="articles[]" value="<%= article.id %>">     
					<span>                                                                                                
						
						<a style="font-weight: bold;" href="#" onclick="setMessage3('<%=articles%>', '<%=article.id%>')"><%=article.title%></a>
							
							<!--  Arbitrary code ...  --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- -->
							
				<script>                
                function setMessage3(articles, id) {
			 <!--  Arbitrary code ...  --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- -->
					console.log(id);
					console.log(thisArticles[id].content);
                }
            </script>
        </body>
        </html>
  • Вопрос задан
  • 120 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы