GoHugo tips and tricks, moving away from wordpress @ Cédric Walter | Wednesday, Dec 27, 2023 | 5 minutes read | 983 Words | Update at Sunday, Jan 28, 2024

Why leaving Wordpress for Hugo

  1. If you are the sole person writing posts, using Github Pages as your hosting platform might be a good option for you. This will allow you to focus on creating content without worrying about technical aspects such as security, updates, and maintenance (Bye bye Wordpress, plugins, PHP, Linux, Mysql).
  2. HTML is indeed fast and secure, especially when combined with properly optimized images. You can use a tool like Google PageSpeed Insights to analyze your website’s performance and identify areas for improvement.
  3. The ability to search and replace text in your files is a useful feature that can help you maintain consistency and accuracy across your content. This can be done using a text editor such as Visual Studio Code, which offer advanced search and replace functionality.
  4. As a software engineer, it makes sense for me and I enjoy working with Visual Studio and utilizing plugins (e.g. Visual Studio’s Markdown Extension) to enhance my workflow. You can explore various extensions for Visual Studio!
  5. Backup and versioning is done using Github only drawback I currently see is that the free hosting of github pages can stop anytime.

LastMod alsways up to date

Instead of defining lastmod in front matter, use the git author date or the file modification time when displaying .Lastmod on a page.

See:

With this site configuration…

enableGitInfo = true

[frontmatter]
lastmod = [':git', ':fileModTime']

…the .Lastmod page method will first try to retrieve the git author date. If that fails, it will look at the file modification time (mtime).

Use archetype

Create a file in your theme folder, e.g. in themes/dream/archetypes/posts.md

---
title: {{ replace .TranslationBaseName "-" " " | title }}
date: {{ .Date }}
cover: /cover.webp
summary: "summary"
categories:
  - category1
tags:
  - tag1
---
Cut out summary from your post content here.
The remaining content of your post.

It will be use when invoking:

hugo new content posts/n-intersting-post.md

Some awesome shortcode

Dynamic TOC highlighting and collapsible functionality

see https://github.com/tscanlin/tocbot

Custom code, not as good as TocBot

Hugo TableOfContents that highlight when scrolling in JQuery

Add to your main javascript file

$(document).ready(function () {
      // collapse levels with more than 1 child
      $('#TableOfContents li').each(function() {
        if ($(this).children('ul').length >= 1) {
          $(this).children('ul').slideToggle();
          $(this).toggleClass('collapsed');
        }
      });

      // make them clickable
      $('#TableOfContents li').click(function(event) {
        event.stopPropagation();
        if ($(this).children('ul').length >= 1) {
          $(this).children('ul').slideToggle();
          $(this).toggleClass('collapsed');
        }
      });

    const toc = $('#TableOfContents');
    if (toc.length) {
        const links = toc.find('a');
        if (links.length) {
            const observer = new IntersectionObserver(els => els.forEach(el => {
                const id = el.target.id;
                id && el.isIntersecting && links.each(function() {
                    const $this = $(this);
                    $this.toggleClass('active', $this.attr('href') === '#' + id);
                });
            }));

            $('h1,h2,h3,h4,h5,h6').each(function() {
                const $this = $(this);
                $this[0].nodeType === 1 && observer.observe($this[0]);
            });
        }
    }

})

use this css or modify to your liking

.active {
    background-color: #ccff00!important; /* Highlight color, you can change this */
    color: #fff !important; /* Text color, you can change this */
    text-decoration: none; /* Remove underlines, adjust as needed */
    transition: background-color 0.3s ease; /* Smooth transition effect */
}

.active:hover {
    background-color: #ccff00; /* Darker highlight color on hover, you can change this */
}

.collapsed {
    list-style-type: none; /* Remove default list item marker */
}

.collapsed:before {
    content: '+ '; /* Set content to a plus symbol followed by a space */
    display: inline-block; /* Ensure the content is treated as a block element */
    width: 1em; /* Adjust the width as needed */
    margin-right: 5px; /* Adjust the spacing to your preference */
}

Process css and js

at the place you use your CSS

{{ $semanticCss := resources.Get "/css/semantic.min.css" }}
{{ $semanticCss = $semanticCss | resources.PostCSS }}
{{ if hugo.IsProduction }}
   {{ $semanticCss = $semanticCss | minify | fingerprint | resources.PostProcess }}
{{ end }}
<link href="{{ $semanticCss.RelPermalink }}" rel="stylesheet" />

Some useful bash scripts for Hugo blog owner

These are useful to clean up or maintain a Hugo blog

Normalize filename extensions to lowercase

This avoid any mess like .JPG .Jpg .webp and so on

[!CAUTION] To be run ONLY in your static folder!

find . -type f | while read -r file; do
    extension=$(echo "$file" | awk -F. '{print tolower($NF)}')
    mv "$file" "${file%.*}.$extension"
done

Fix jpg to jpeg

jpg is old pre windows 1992, consistently use jpeg

[!CAUTION] To be run ONLY in your static folder!

find . -type f -name "*.jpg" -exec sh -c 'mv -i "$0" "${0%.jpg}.jpeg"' {} \;

creating thumbs files

Create thumbs run only in gallery folder, I use a shortcode foldergallery.html

[!CAUTION] To be run ONLY in your static folder!

for i in `find . -type f ! -name "*-thumb.jpeg" -name "*.jpeg"`; do echo $i; if [ -f ${i%.*}-thumb.jpeg ]; then continue; fi; convert $i -resize 352x352 ${i%.*}-thumb.jpeg; done

WEBP next generation image format

Create webp, I use a shortcode picture.html

[!CAUTION] To be run ONLY in your static folder! recursive and support space in path

find . -name "*.webp" -delete

find . -type f -name "*.jpeg" -exec sh -c 'cwebp -q 80 "$0" -o "${0%.jpeg}.webp"' {} \;
find . -type f -name "*.png" -exec sh -c 'cwebp -q 80 "$0" -o "${0%.png}.webp"' {} \;
find . -type f -name "*.gif" -exec sh -c 'cwebp -q 80 "$0" -o "${0%.gif}.webp"' {} \;

Hugo Shortcode

Optimize images

{{ $image := .Get "src" }}
{{ $alt := .Get "alt" }}
{{ $avif := $image | relURL | replaceRE `(\.\w+)$` ".avif" | absURL }}
{{ $webp := $image | relURL | replaceRE `(\.\w+)$` ".webp" | absURL }}

<figure>
  <picture>
    <source type="image/webp" srcset="{{ $webp }}">

    <img loading="lazy" src="{{ $image | absURL }}" title="{{ $alt }}" alt="{{ $alt }}"
    >
  </picture>
  <figcaption>{{ $alt }}</figcaption>
</figure>

Usage:

![](/hewlett-packard/hp49boot.gif)

Related content

I cleaned my blog…removed 3200 posts!

I cleaned my blog…removed 3200 posts!

Friday, Aug 25, 2023

It is a sad day when your delete lots of posts in your personal blog, some posts were as old as 1997, but why cleaning blog of old articles is a good move?
2 minutes read
Dynamic IP at home, no problem with ddclient and Cloudflare

Dynamic IP at home, no problem with ddclient and Cloudflare

Thursday, Feb 29, 2024

ddclient is an open-source Perl-based client used to update dynamic DNS entries for various DDNS service providers. It supports a wide range of protocols, including DynDNS, No-IP, DuckDNS, Cloudflare, and many others, making it a flexible choice for users with diverse needs.
3 minutes read
Use generative AI assistants like ChatGPT for FREE

Use generative AI assistants like ChatGPT for FREE

Wednesday, Feb 7, 2024

If youre intrigued by the concept of AI assistants like ChatGPT, Google Bard, Bing Chat, or others, you might have certain apprehensions regarding privacy, expenses, and beyond. This is where Llama 2 steps in. Llama 2 is an open-source large language model engineered by Meta, boasting variants spanning from 7 billion to 70 billion parameters.
4 minutes read

© 1997 - 2024 Cédric Walter blog

Powered by Open Sources technologies

avatar

Cédric WalterA true selfless act always sparks another

6s a1 acide-hyaluronique acma adaptability advocate-for-change ai airplane algorand alice-hlidkova-author alpine alps altruism-vs-commercialization antique-scooters antiseptic-rinse apache arcade arcade-gaming armattan art artemis artemis-viper artistic-expression atlassian authenticity-in-writing authenticity-matters avis bag bambulab bash bean bennu bernardet bestwishes betaflight betruger beware bien-vivre bien-être bien-être-physique bio bioethics bitcoin blessures-sportives blockchain blockchain-consensus-encyclopedia blockchain-systems blog book-review books bots Bought box brand-authenticity brand-integrity brand-protection breaking-barriers business-management business-milestones business-strategy business-success business-transformation businessbooks byzantine-fault-tolerance calculator calibre calibre-web camera case-studies cc2500 cgm-next challenges changement-de-vie channel-setup cheaper cherry-blossoms chirurgie-orthopédique choosing-fbl-gyro ci/cd classic-games classic-scooters classic-vespa climb climbing codefest collectible-scooters collectibles collection collector color competition consensus-algorithms consensus-mechanisms console consommation-responsable consumer-awareness containerization contest control-surfaces controller copy corticostéroïdes counterfeit-awareness counterfeit-culture counterfeit-market counterfeit-vs-authentic covid19 creating croissance-personnelle cryptocurrency cultural-experience cultural-richness curve-adjustments customer-discovery cve-issues dance-dreams death decentralization decentralized dental-hygiene dependency Design development devfest devops distributed-ledger-technology diverse-perspectives diy-dental diy-health dji docker docker-compose docker-hosting docker-networking docker-registry docker-security dont-buy dotnet Download downloading dreams-and-reality drone dynamic-ip désencombrement développement-personnel développement-spirituel ecology edgetx elrs elta emotional-challenges emotional-hurdles empowering-narrative endpoints engelberg Ensitm entrepreneurial-lessons entrepreneurial-mindset entrepreneurs entrepreneurship entrepreneurship-books Essaim essentially ethereum ethical-dilemmas evoque execution exercices-de-renforcement exercise-form facebook failure-analysis failure-stigma failure-to-success fake fake-apparel fake-brands fake-goods family family-building family-dynamics fashion-ethics fashion-fraud fbl-controllers fbl-system-compatibility fbl-system-features fbl-system-reviews fertility-struggles finance-books finances-personnelles financial-modeling financiallanning firearm firmware-customization firmware-issues fissure-horizontale fitness-routine fitness-tips flexibilité flight-controller flybarless-advantages flybarless-systems foss fpv frame France freestyle fresh-breath friendship-goals front gallery game-music gameplay-mechanics gamer-community games gaming-culture gaming-enthusiast gaming-history gaming-legacy gaming-nostalgia generative-ai genou gestion-de-ladouleur gestion-du-temps git global-impact google green-tea green-tea-mouthwash growth-hacking-books growth-mindset guide hackathon hackday hackfest health-and-wellness helicopter helicopter-community helicopter-gyro helicopter-tuning herbal-mouthwash hewlettpackard historical-scooters hobbies hobby hobbyist-blog holidays holistic-oralcare hollidays home-remedy home-workouts homelab homemade-oralcare honda honesty honey hornet how-to howTo https hugo human-connection hygiene-routine icecream iconic-scooters iflight iflightnazgulevoque immich indoor industrial-shit industry injections-intra-articulaires injury-prevention innovation innovation-books innovation-journey ios japan-travel japanese-cuisine jar java jdk11 jellyfin joint-health junit jupiter kitchen knee-rehabilitation knee-stability knockoff-alert kyoto lacoste lacoste-counterfeit lambretta landmarks leadership leadership-books lean-startup learning-from-failure leg-day leg-workouts legal-complexities legit-fashion let's-encrypt libération life-transformations link linux llm local-traditions m2evo macos magical-adventure magician-lord main make manurhin manurhin-sm75 mapping marathon market-research marketing-books maven me medical medical-advancements metakernel miami-entertainment mid-century-scooters migration mindset-shifts minimalisme minimum-viable-product minty-fresh mixer-settings mk3 mk4 mobilité model-setup modern-family modern-motherhood moon moral-encounters motherhood-dilemmas motorcycle mount mountain mountains mouth-rinse mouthwash-ingredients mouthwash-recipe Mulhouse muscle-activation music mvs mycollection ménisque NASA natural-mouthwash nature nazgul neo-geo-aes neogeo network new-bookrelease nginx-proxy north-face north-face-replica nostalgic-scooters nv14 objectifs old-school-scooters omphobby open-source open-source-rc opensource opentx openvpn oral-care oral-health organizer osaka oss overcoming-challenges p1p p1s parental-rights parenthood-reflections parts passion patella-health persistence personal-relationships photos physical-therapy physiothérapie pivot-strategy pixel-art planet plasma-riche-en-plaquettes platform plex pluto pretty-girl-complex privacy product-market-fit productivity-books proof-of-stake proof-of-work protect-your-style prusa prusa-research public-image quadcopter quadriceps-strength radio-control radio-programming radiomaster rare-scooters raspberrypi raspbian rates-configuration rc rc-community rc-configuration rc-firmware RC helicopter rc-helicopter-electronics rc-helicopter-enthusiasts rc-helicopter-setup rc-helicopter-technology rc-helicopter-tips rc-helicopters rc-modeling rc-simulator realdebrid realflight receiver reflex-xtr refreshing-breath rehabilitation-exercises relations-personnelles relationship-complexities released remote remote-control-flying reproductive-ethics resilience-in-business resilient-women restored-scooters retro-gaming retro-gaming-community retro-gaming-console retro-scooters reverse-proxy rhythms-of-life risk-management robotic router rx réadaptation rééducation sab sab-raw-420 sab-raw-580 sab-raw-700 sales-books santé-articulaire santé-mentale scooter-enthusiast scooter-memorabilia scooters security-nightmare self-leveling-helicopter server-configuration servo-config skydiving snk snk-corporation snk neo geo soap social-issues solex space spams sport ssl-termination ssl/tls startup-books startup-failure static-code-generator steam strategic-networking streaming strength-training success-stories sun support surrogacy-agency surrogacy-journey surrogacy-narratives swiftui swiss switzerland team team-building team-dynamics teeth-cleaning temples-and-shrines tendermint terrot thérapie-physique tokyo torvol traefik traitement-des-fissures transmitter transmitter-firmware travel travel-tips trouver-du-sens tunnel turning-setbacks-into-success tutorial tx unconventional-strategies vacation velosolex vespa viaferrata video video-game-review vintage vintage-scooters vintage-two-wheelers vintage-vespa vintagegaming vmo-exercises warez web-security wind winner winterthur women-supporting-women wordpress workout-progression x1c zurich zyxel zyxel-avoid zyxel-not-serious-with-security zyxel-outdated zyxel-router-not-good équilibre
Me

Cédric Walter is a French-Swiss entrepreneur, investor, and software engineer based in Zurich, Switzerland. He spent his career developing software applications for Swiss insurance companies to handle billions of dollars in premiums. He cofounded Innoveo AG and as the software architect developed the no-code platform designed to reduce the manual coding that powers many software apps. As an active participant in the European hacking community, he works on many open source projects including blockchain. Cédric is a winner of multiple hackathons. His expertise include designing back end, event-based, and blockchain systems. Cédric is also the founded Disruptr GmbH, a software development company that offers full spectrum of services for businesses of all sizes.

JAVA full-stack developer since 2000, in Blockchain since 2017, Certified Scrum Master 2012, Corda Certified Developer in 2019, Ethereum smart contract expert in the SWISS Blockchain Security working group

Hackathons

  • HackZurich 2022 – Level Up in top 25 finalist among 134 submissions
  • SBHACK21 – SwiFi winner of best Solution on Algorand, overall Winner 3rd Prize, CV Labs Fast Track Ticket
  • HackZurich 2020 Europe’s Biggest Hackathon winner in category Migros
  • SBHACK19 – LendIt winner of Swiss biggest Blockchain Hackathon. On chain insurance and ledger for agricultural land soil.
  • Member of the Bitcoin Association Switzerland and Cryptovalley association Switzerland,

PGP: DF52 ADDA C81A 08A6

Copyright information

All editorial content and graphics on our sites are protected by U.S. copyright, international treaties, and other applicable copyright laws and may not be copied without the express permission of Cedric Walter, which reserves all rights. Reuse of any of Cedric Walter editorial content and graphics for any purpose without The author ’s permission is strictly prohibited.

DO NOT copy or adapt the HTML or other code that this site creates to generate pages. It also is covered by copyright.

Reproduction without explicit permission is prohibited. All Rights Reserved. All photos remain copyright © their rightful owners. No copyright infringement is intended.

Disclaimer: The editor(s) reserve the right to edit any comments that are found to be abusive, offensive, contain profanity, serves as spam, is largely self-promotional, or displaying attempts to harbour irrelevant text links for any purpose.

Others

If you like my work or find it helpful, please consider buying me a cup of coffee ☕️. It inspires me to create and maintain more projects in the future. 🦾

It is better to attach some information or leave a message so that I can record the donation 📝 , thank you very much 🙏.

Reproduction without explicit permission is prohibited. All Rights Reserved. All photos remain copyright © their rightful owners. No copyright infringement is intended.