How to custom Icon in menu
In this section, you can learn how to add icon in your menu navigation and how to highlight menu when you click
In the [Hugo introduction] blog, I have shown how the menu is added in hugo. Following the previous article on how to customize social media, did you think that to display the menu you would need to add an icon property? 😂😂😂
Head to config.toml file,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
# setup menu
sectionPagesMenu = "main"
[menu]
[[menu.main]]
name = "Home"
pre = '<i class="fa-solid fa-house"></i>'
url = "/"
weight = 1
[[menu.main]]
name = "My Blog"
pre = '<i class="fa-solid fa-paper-plane"></i>'
url = "/posts/"
identifier = "posts"
weight = 2
[[menu.main]]
name = "Tags"
pre = '<i class="fa-solid fa-tag"></i>'
identifier = "tags"
url = "/tags/"
weight = 3
[[menu.main]]
name = "Abouts"
pre = '<i class="fa-sharp fa-solid fa-medal"></i>'
identifier = "about"
url = "/about/"
weight = 4
|
We add icon in “pre”. The icon library I use is the common fontawesome.
In the menu.html, just using hugo syntax {{.Pre}} to display icon.
1
2
3
4
5
6
7
8
|
{{ range .Site.Menus.main }}
<a href="{{ .URL }}" title="{{ .Name }}">
<li class="hover">
{{ .Pre }}
{{ .Name }}
</li>
</a>
{{ end }}
|
This is an additional attribute that highlights a menu when it is clicked on.
We need to use the built-in syntax, such as “eq” “delimit” “split”. More infomation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
{{ $currentPage := . }}
{{ range .Site.Menus.main }}
{{ $menu_item_url := .URL | relLangURL }}
{{ $page_url:= $currentPage.RelPermalink | relLangURL }}
{{ $segments1 := delimit (split $menu_item_url "/") "/" }}
{{ $segments2 := delimit (split $page_url "//") "/" }}
{{ $section1 := first 6 $segments1 }}
{{ $section2 := first 6 $segments2 }}
<!-- {{ printf "segments1 = %s " $section1 }}
{{ printf "segments2 = %s " $section2 }} -->
<a href="{{ $menu_item_url }}" title="{{ .Name }}">
<li class="hover {{if eq $section2 $section1 }} active {{end}}">
{{ .Pre }}
{{ .Name }}
</li>
</a>
{{ end }}
|
In tailwind.css, I add a new class name active. You can overwrite your active attributes, such as color, box-shadow, size and so on.
1
2
3
4
|
#menu .active {
color: #ffb703;
font-size: 1.15rem;
}
|