Как перенести коллекцию из ejs в функцию javascript?
Как перенести коллекцию из ejs в функцию javascript?
Решение-1
<a style="font-weight: bold;" href="#" onclick="setMessage3('<%=articles%>', '<%=article.id%>')"><%=article.title%></a>
<script>
function setMessage3(articles, id) {
<!-- Arbitrary code ... --- --- -->
console.log(id);
console.log(thisArticles[id].content);
}
</script>
Решение-2
<script>
function setMessage4(id) {
let thisArticles = '<%=articles%>';
console.log(thisArticles[id].content);
}
</script>
Обновление-1
Главная цель: выполнить на странице Master-Detail.
Пользователь кликает по <a> в результате справа отображается текст статьи.
Логика.
Из контроллера получаем коллекцию.
В index.ejs строим левое меню с помощью:
<% articles.forEach((article, index) => { %>
<a style="font-weight: bold;" href="#"><%=article.title%></a>
Далее пользователь кликает по <a>.
Передаём id с помощью <%=article.title%> в функцию JS.
Далее с помощью JS:
- получить коллекцию
articles; - получить элемент коллекции
article = articles[i]; - получить свойство
article.content; - отобразить свойство
article.contentв элементе html страницы(Пример: отобразить в элементе div);
index.ejs (исходный... Потом планируется переделать)
<!doctype html>
<html lang="ru">
<head>
<!-- Кодировка веб-страницы -->
<meta charset="utf-8">
<!-- Настройка viewport -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>...</title>
<!-- Bootstrap CSS (jsDelivr CDN) -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- Bootstrap Bundle JS (jsDelivr CDN) -->
<!--
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
-->
</head>
<!-- <body> -->
<body>
<!-- class="container" -->
<div class="container">
<!-- div -->
<div class="border border-success border-3 p-2 vh-100 d-flex flex-column">
<!-- HEADER --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- ---->
<!-- <header class="py-4 text-center text-uppercase fs-4 bg-primary bg-gradient text-white">
Header
</header> -->
<!-- ROW --- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- --- --- -->
<div class="row py-3 flex-grow-1">
<!-- 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>
<span>
<a style="font-weight: bold;" href="#"><%=article.owner%></a>
</span>
<span>
<a style="font-weight: bold;" href="#"><%=article.number%></a>
</span>
<span>
<a style="font-weight: bold;" href="#"><%=article.pos%></a>
</span>
<!-- <th scope="row"><%= article.id %></th> -->
<!-- <td><%= article.title%></td> -->
<!-- <td><%= article.content %></td>
<td><%= article.background %></td> -->
<!-- <td><%= article.owner %></td> -->
<!-- <td>@<%= article.number %></td> -->
<!-- <td>@<%= article.pos %></td>
<td>@<%= article.lang %></td> -->
</li>
<%})%>
</ul>
<%}%>
</ul>
</aside>
</div>
<!-- PLACEHOLDER --- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- -->
<div class="col-9 d-flex">
<main class="bg-light bg-gradient w-100 d-flex justify-content-center align-items-center text-dark fs-5 border border-success border-3">
Placeholder
</main>
</div>
<!-- RIGHTBAR --- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- --- --- -- -->
<!-- <div class="col-3 d-flex">
<aside class="bg-danger bg-gradient w-100 d-flex justify-content-center align-items-center text-white fs-5">
Right Bar
</aside>
</div> -->
</div>
<!-- FOOTER -->
<!-- <footer class="py-4 bg-info bg-gradient text-center text-uppercase fs-4 text-white">
Footer
</footer> -->
</div>
</div> <!-- .container -->
</body>
</html>
SQL
CREATE DATABASE socka;
--
-- Структура таблицы `articles`
--
DROP TABLE IF EXISTS `articles`;
CREATE TABLE IF NOT EXISTS `articles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`content` text,
`background` text,
`owner` int(11) DEFAULT NULL,
`pos` int(11) DEFAULT '0',
`lang` int(11) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=275 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
--
-- Структура таблицы `articles`
--
INSERT INTO `articles` (`id`, `title`, `content`, `background`, `owner`, `pos`, `lang`) VALUES
(1, 'Articles-1', 'Content--Articles-1', NULL, NULL, 0, 1),
(2, 'Articles-1-1', 'Content--Articles-1-1', NULL, 1, 0, 1),
(3, 'Articles-1-2', 'Content--Articles-1-2', NULL, 1, 0, 1),
(4, 'Articles-1-3', 'Content--Articles-1-3', NULL, 1, 0, 1),
(5, 'Articles-1-1-1', 'Content--Articles-1-1-1', NULL, 2, 0, 1),
(6, 'Articles-1-1-2', 'Content--Articles-1-1-2', NULL, 2, 0, 1),
(7, 'Articles-1-1-3', 'Content--Articles-1-1-3', NULL, 2, 0, 1),
(8, 'Articles-2', 'Content--Articles-2', NULL, NULL, 0, 1),
(9, 'Articles-3', 'Content--Articles-3', NULL, NULL, 0, 1),
(10, 'Articles-4', 'Content--Articles-4', NULL, NULL, 0, 1),
(11, 'Articles-5', 'Content--Articles-5', NULL, NULL, 0, 2);
Ответы (1 шт):
Можно рисовать список ссылок как и указано в вопросе. В функцию показа статьи формировать ид для показа содержимого.
<% articles.forEach((article, index) => { %>
<a style="font-weight: bold;" href="#" onclick="showArticle('article-content-<%=article.id%>')"> <%=article.title%></a>
Так же ниже в блоке вывода данных рисовать содержимое статьи, id должен совпадать из , но не показывать его display: none
<% articles.forEach((article, index) => { %>
<div style="display: none" class="content" id="article-content-<%=article.id%>">
<%=article.content%>
</div>
А при клике по ссылке показывать нужную статью, пример на чистом js
function showArticle(articleId) {
for (let elementsByClassNameElement of document.getElementsByClassName('content')) {
elementsByClassNameElement.style.display = 'none';
}
document.getElementById(articleId).style.display = 'block';
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div class="container d-flex">
<div class="col-3 d-flex">
<div class="border border-success border-3 p-2 vh-100 d-flex flex-column">
<a style="font-weight: bold;" href="#" onclick="showArticle('article-content-1')">content 1</a>
<a style="font-weight: bold;" href="#" onclick="showArticle('article-content-2')">content 2</a>
<a style="font-weight: bold;" href="#" onclick="showArticle('article-content-3')">content 3</a>
</div>
</div>
<div class="col-9 d-flex">
<aside class="bg-danger bg-gradient w-100 d-flex justify-content-center align-items-center text-white fs-5">
<div class="content" id="article-content-empty">
Empty content
</div>
<div style="display: none" class="content" id="article-content-1">
Content 1
</div>
<div style="display: none" class="content" id="article-content-2">
Content 2
</div>
<div style="display: none" class="content" id="article-content-3">
Content 3
</div>
</aside>
</div>
</div>

