Skip to content

Commit

Permalink
Add language switch to navbar
Browse files Browse the repository at this point in the history
  • Loading branch information
erdnaxe committed Oct 30, 2024
1 parent 96dcd9d commit 37c92ad
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
2 changes: 2 additions & 0 deletions assets/js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import advancedFormat from "dayjs/plugin/advancedFormat";
import times from "./theme/times";
import styles from "./theme/styles";
import highlight from "./theme/highlight";
import languageSwitch from "./theme/languageSwitch";

import alerts from "./utils/alerts";
import tooltips from "./utils/tooltips";
Expand All @@ -22,6 +23,7 @@ CTFd.init(window.init);
styles();
times();
highlight();
languageSwitch();

alerts();
tooltips();
Expand Down
26 changes: 26 additions & 0 deletions assets/js/theme/languageSwitch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export default () => {
const form = document.getElementById('language-switch')
form.addEventListener('submit', async e => {
// Do not open API page
e.preventDefault()

// Submit form
let data = new URLSearchParams(new FormData(form));
const response = await fetch(form.action, {
method: 'post',
body: data
});
if (!response.ok) {
throw new Error(`Language change failed: ${response.status}`);
}

// Reload with new language
window.location.reload()
})

document.querySelectorAll("#language-switch input[type='radio']").forEach(el => {
el.addEventListener('change', e => {
form.requestSubmit()
})
});
};
21 changes: 21 additions & 0 deletions templates/components/navbar.html
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,27 @@
</a>
</li>
{% endif %}

<li class="nav-item dropdown">
<button class="nav-link dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
<i class="fas fa-language d-none d-md-inline"></i>
<span class="d-sm-inline d-md-none">
<i class="fas fa-language pe-1"></i>
{% trans %}Change language{% endtrans %}
</span>
</button>
{%- with form = Forms.lang.LanguageForm(language=get_locale()) %}
<form action="/api/v1/lang" method="post" id="language-switch">
<ul class="dropdown-menu dropdown-menu-end">
{%- for subfield in form.language %}
<li>{{ subfield(class="btn-check") }}{{ subfield.label(class="dropdown-item") }}</li>
{%- endfor %}
</ul>
{{ form.nonce() }}
</form>
{%- endwith %}
</li>

<li class="nav-item">
<button class="nav-link theme-switch" type="button">
<span data-bs-toggle="tooltip" data-bs-placement="bottom" title="{% trans %}Toggle theme{% endtrans %}">
Expand Down

0 comments on commit 37c92ad

Please sign in to comment.