Skip to content

Instantly share code, notes, and snippets.

@Ivana-
Last active January 5, 2024 00:51
Show Gist options
  • Save Ivana-/44624440795446a228b0e499f3f5d556 to your computer and use it in GitHub Desktop.
Save Ivana-/44624440795446a228b0e499f3f5d556 to your computer and use it in GitHub Desktop.
Bare-bones dynamic html using fetch in body
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.unauthorized-display-none { display: none }
.authorized-display-none { display: none }
</style>
</head>
<body>
<div class="unauthorized-display-none">
<span><a href="/login">Войти</a></span>
<span><a href="/register">Зарегистрироваться</a></span>
</div>
<div class="authorized-display-none">
<span id="user-login"></span>
<span><a href="/logout">Выйти</a></span> <!-- Тут надо кнопку с фетчем POST! -->
</div>
<!-- Other elements -->
<p class="authorized-display-none"><a href="/app">Контент для авторизованных</a> в полной версии.</p>
<script>
async function fetchProcessUserData() {
const resp = await fetch("/user-data", { method: "GET" })
authorized = false
if (resp.ok) {
const data = await resp.json()
if (data) {
const { login, created } = data
const elem = document.getElementById("user-login")
elem.textContent = login
authorized = true
}
}
const tag = authorized ? "authorized-display-none" : "unauthorized-display-none"
const elements = document.getElementsByClassName(tag)
for (let i = elements.length - 1; i >= 0; i--) elements[i].classList.toggle(tag)
}
fetchProcessUserData()
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment