我想知道如何更新所有页面的链接。
我有一个通用的头文件,其中包含具有语言下拉列表的导航栏。 当前,所有页面都使用相同的头文件, 可以说,如果我选择一种下拉语言,它将导航到后端路由,
选择下拉菜单时
在“索引”页面上,下拉网址应为/en``/th
,
在“关于”页面上,下拉网址应为/en/about
/th/about
在“联系人”页面上,下拉网址应为/en/contact
,th/about
所以我的问题是因为我有一个通用的标题,当我进入各个页面时,如何更新下拉URL中的链接。 如何使用前端/后端,有点困惑
//language.js
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.render('index.ejs'});
});
module.exports = router;
//aboutus.js
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.render('aboutus.ejs');
});
module.exports = router;
header.ejs
<body>
<nav>
<ul>
<li class="nav-item">
<a class="nav-link" href="/en/about" style="margin-right: 1.5rem!important;">about us</a>
</li>
<li class=" nav-item">
<a class="nav-link" href="/en/contact"
style="margin-right: 1.5rem!important;">contact us</a>
</li>
</ul>
<div class="dropdown">
<button id="language" class="btn btn-warning dropdown-toggle" type="button" id="dropdownMenu2"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="clickButton()">
English
</button>
<div id="languagelist" class="dropdown-menu" aria-labelledby="dropdownMenu2" onclick="clickItem(); return false">
<a class="dropdown-item" href="/en">English</a> //change this link according to the page
<a class="dropdown-item" href="/th">Thai</a>//change this link according to the page
</div>
</div>
</nav>
</body>
//index.ejs
<%- include header.ejs %>
<h1>Welcome to My Site</h1>
//about.ejs
<%- include header.ejs %>
<h1>About us</h1>
答案 0 :(得分:0)
<div id="languagelist" class="dropdown-menu" aria-labelledby="dropdownMenu2" onclick="clickItem(); return false">
<a class="dropdown-item" href="javascript:" onclick="updateLang("en")">English</a> //change this link according to the page
<a class="dropdown-item" href="javascript:" onclick="updateLang("th")">Thai</a>//change this link according to the page
</div>
Script for the updatelang
updateLang(val){
var url = new URL(location.href);
var query_string = url.search;
var search_params = new URLSearchParams(query_string);
// new value of "lang" is set to "th" val = "th"
search_params.set('lang', val);
// change the search property of the main url
url.search = search_params.toString();
// the new url string
var new_url = url.toString();
// output : http://demourl.com/path?lang=th
console.log(new_url);
location.replace(new_url)
}
you can send query parameter to backend
router.get('/', function (req, res) {
let lang = req.query.lang;
// based on lang you can send file
res.render('aboutus.ejs');
});