Hugo

Google Analytics 4 설치 - Hugo 깃허브

개요

  • Google Analytics 4 설치 과정을 정리하였다.

사전준비

  • 본 글에서는 Google Analytics 4 관련 설명은 생략한다.
  • 어느정도 관련 도구를 이해한다는 전제 조건에서 글을 정리한다.

단계별 설치 과정

  • 단계별로 설치 과정을 알아보자.

(1) GA4 추적 ID 가져오기

  • Google Analytics 4 에서 추적 코드를 받는다.
  • 추적 코드는 Admin - Data Streams에서 확인이 가능하다.

  • Add stream 에서 Hugo Website 주소를 입력한 후 설정을 하면 된다.

  • 그럼 MEASUREMENT ID 확인이 가능하다.

    • G-XXXXXXX 시작하는 ID만 있으면 충분하다.
  • 그 외 나머지 GA4 설정은 관련 자료를 참고해서 설정한다.

Google Adsense with Hugo

동기부여

  • 블로그 광고수익 비교 글을 보게 되었다.

  • 그런데, 현재 운영중인 이 블로그의 일일 방문자수가 300-400명이어서 방치하면 안될 것 같았다.

  • 간단하게 Google Adsense를 Hugo Website에 추가하도록 한다.

사전준비

Google Adsense

  • 우선 Google Adsense에 접속한다.

  • Google Ads에서 아래 그림과 같이 사이트를 클릭한다.

  • 사이트 추가 버튼을 누른다.

Hugo 깃허브 블로그 - Windows (2022)

패키지 관리자 설치

Untitled

Chocolatey (Windows)

  • If you are on a Windows machine and use Chocolatey for package management, you can install Hugo with the following one-liner:
  • 우선 PowerShell을 관리자로 실행 후, 아래와 같이 Chocolately를 설치한다.
    • 명령어 : Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('[https://community.chocolatey.org/install.ps1](https://community.chocolatey.org/install.ps1)'))
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
                                                                                                                        
새로운 크로스 플랫폼 PowerShell 사용 https://aka.ms/pscore6                                                                                                                                                                                     
PS C:\WINDOWS\system32> Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
Forcing web requests to allow TLS v1.2 (Required for requests to Chocolatey.org)
Getting latest version of the Chocolatey package for download.
Not using proxy.
Getting Chocolatey from https://community.chocolatey.org/api/v2/package/chocolatey/1.1.0.
Downloading https://community.chocolatey.org/api/v2/package/chocolatey/1.1.0 to C:\Users\512-24\AppData\Local\Temp\chocolatey\chocoInstall\chocolatey.zip
Not using proxy.
Extracting C:\Users\512-24\AppData\Local\Temp\chocolatey\chocoInstall\chocolatey.zip to C:\Users\512-24\AppData\Local\Temp\chocolatey\chocoInstall
Installing Chocolatey on the local machine
Creating ChocolateyInstall as an environment variable (targeting 'Machine')
  Setting ChocolateyInstall to 'C:\ProgramData\chocolatey'
WARNING: It's very likely you will need to close and reopen your shell
  before you can use choco.
Restricting write permissions to Administrators
We are setting up the Chocolatey package repository.
The packages themselves go to 'C:\ProgramData\chocolatey\lib'
  (i.e. C:\ProgramData\chocolatey\lib\yourPackageName).
A shim file for the command line goes to 'C:\ProgramData\chocolatey\bin'
  and points to an executable in 'C:\ProgramData\chocolatey\lib\yourPackageName'.

Creating Chocolatey folders if they do not already exist.

WARNING: You can safely ignore errors related to missing log files when
  upgrading from a version of Chocolatey less than 0.9.9.
  'Batch file could not be found' is also safe to ignore.
  'The system cannot find the file specified' - also safe.
chocolatey.nupkg file not installed in lib.
 Attempting to locate it from bootstrapper.
PATH environment variable does not have C:\ProgramData\chocolatey\bin in it. Adding...
경고: Not setting tab completion: Profile file does not exist at
'C:\Users\512-24\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'.
Chocolatey (choco.exe) is now ready.
You can call choco from anywhere, command line or powershell by typing choco.
Run choco /? for a list of functions.
You may need to shut down and restart powershell and/or consoles
 first prior to using choco.
Ensuring Chocolatey commands are on the path
Ensuring chocolatey.nupkg is in the lib folder
PS C:\WINDOWS\system32>

choco를 활용한 Hugo 설치

  • 설치 시, 관리자로 PowerShell을 실행한다.
$ choco install hugo-extended -confirm
  • hugo version을 확인한다.
$ hugo version
hugo v0.97.0-c07f3626e7c8160943591f4d209977efa02c3dca windows/amd64 BuildDate=2022-04-14T08:45:07Z VendorInfo=gohugoio
PS C:\WINDOWS\system32>

Git & Github 설치

  • 이제 Git을 설치하도록 한다. Git이 있어야 배포를 할 수 있기 때문에 반드시 설치한다.
  • Github 회원가입도 안했다면 회원가입을 진행하도록 한다.

Hugo 명령어를 활용한 첫번째 싸이트 만들기

  • 간단한 명령어를 활용하여 싸이트를 생성한다.
    • 명령어 : hugo new site your_blog_name
  • 필자는 폴더명을 myblog로 지정했다.
PS C:\Users\your_name\Desktop> hugo new site myblog
Congratulations! Your new Hugo site is created in C:\Users\512-24\Desktop\myblog.

Just a few more steps and you're ready to go:

1. Download a theme into the same-named folder.
   Choose a theme from https://themes.gohugo.io/ or
   create your own with the "hugo new theme <THEMENAME>" command.
2. Perhaps you want to add some content. You can add single files
   with "hugo new <SECTIONNAME>\<FILENAME>.<FORMAT>".
3. Start the built-in live server via "hugo server".

Visit https://gohugo.io/ for quickstart guide and full documentation.

Github & Submodule 설정

  • 우선 Github 세팅을 먼저 할 것이다.

깃허브 Repo 작성

  • myblog & username.github.io 두 개의 repo를 작성한다.
  • 깃허브와 현재 작성중인 폴더(myblog)를 연결한다.
    • 모든 명령어는 myblog/ 에서 적용한다.
    • 이 때 public 폴더가 있으면 지워준다.
cd myblog
rm -rf public
echo "# myblog" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/rain0430/myblog.git
git push -u origin main
  • 처음 깃헙을 하시는 분들은 주로 하단에서 에러가 나타날 것이다.
    • 이는 로그인을 하라는 뜻이다. (RUN 아래 코드를 순차적으로 실행)
$ git commit -m "first commit"
Author identity unknown

*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"
  • git commit 부터 다시 순차적으로 실행한다. git push 할 때, sign in 팝업창이 뜰 수도 있다.
  • 이제 서브모듈(Submodule)을 통해서 배포를 진행하려고 한다.
  • git 서브모듈을 추가한다.
    • 이 때, .gitmodules가 뜨는지 확인한다.
    • 또한 rain0430.github.io Repo는 새로 만들어준다.
    • 그리고 다음 명령어을 추가한다.
$ git submodule add -b main https://github.com/rain0430/rain0430.github.io.git public
  • 만약 에러가 난다면, 강제로 실행을 한다.
$ git submodule add -f https://github.com/rain0430/rain0430.github.io.git public

Hugo 기본 싸이트 확인

  • 우선 기본 테마를 설정해본다.
  • 필자는 다음 테마를 설정할 것이다. Codex | Hugo Themes (gohugo.io)
    • 테마 설정 시, 약간의 팁을 드리면, Updated가 최근 날짜인지 확인한다. 최근 날짜가 아니라면 관리가 잘 안되어 테마일수도 있다.
    • 각 테마마다 구체적인 설정 방법이 있기 때문에 각 설치 문서를 참조한다.

Untitled

(Python-Plotly) Plotly 그래프 깃헙 블로그에 올리기

강의 홍보

개요

  • 깃헙 브로그에 동적 시각화를 올리는 방법에 대해 기술한다.
  • 현재까지 찾아낸 것은 이게 최선입니다! 더 나은 것이 있다면 공유 부탁드립니다. (꾸벅)

필수 라이브러리 설치

$ pip install plotly
$ pip install chart_studio
  • plotly의 역할 그래프를 작성하는 기본 도구이며, chart_studio의 역할은 그래프를 plotly 홈페이지 업로드 할 수 있도록 도와주고, 또한 iframe output으로 변환하는 데 도움을 주는 코드이다.

step 01. 그래프 작성

  • 그래프를 작성합니다.
import plotly.express as px
import chart_studio

gapminder = px.data.gapminder()
fig = px.scatter(gapminder.query("year==2007"), x="gdpPercap", y="lifeExp", size="pop", color="continent",
           hover_name="country", log_x=True, size_max=60)
fig.show()
  • 위 출력물은 실제로는 동적 시각화로 구현이 됩니다만, 캡쳐하여 올려 놓습니다.

Hugo Blog 옮기기

개요

  • 새로운 맥을 구입하면서 생긴 여러 에러를 해결하면서 기록으로 남겼다.

선수 학습

  • 본 포스트는 기존 hugo 깃허브 블로그를 운영중인 독자들을 위한 글이다.
  • 만약 깃허브 블로그를 처음 만드시는 분은 공식 홈페이지를 참조하기를 바란다.

기존 블로그 활용

  • 필자는 blog라는 깃허브 repo가 존재하였음
  • 따라서, blog 레포를 내려 받았다.
$ git clone https://github.com/yourname/your_repo.git

상황 1. submodule에 대한 충분하지 못한 이해

  • 필자가 실수한 것이 있다.
  • github에서 submodule은 영어 단어 그대로, 서브 모듈이다. 즉, 한개의 메인 프로젝트가 존재하지만, 다른 프로젝트는 공통으로 사용할 모듈이라는 뜻이다.
  • 다시 정리하자면,
    • 필자에게 메인 프로젝트는 blog 레포에 글을 남기는 것이다.
    • 필자가 필요한 것은 깃허브 블로그에 필요한 mainroad라는 테마(theme) 모듈과, 배포를 위한 public 모듈이다.
  • public은 필자의 깃허브 주소와 연동되어 있는 모듈이라고 생각하면 쉽다.
    • 즉, public과 필자의 깃허브 주소 레포와 하나로 연결되어 있기 때문에, 자동으로 배포가 되는 시스템이다.
  • 여하튼, 필자가 실수한 것은 바로, 저 public에 대한 서브모듈을 생각하지 못했고, 이 에러가 가장 치명적이었다.

해결방안

  • 어떻게 해결할까? Note: 순서를 꼭 잘 지키도록 한다
  • 우선, 깃허브를 내려받으면, 기존 publicthemes/your_theme는 삭제한다.
    • 이유: 캐시가 남아 있는데, 위 두개 삭제를 하지 않으면 에러의 무한루프에 빠진다.
    • 아래 코드는 에러의 한 예다.
blog % git commit -m "updated"
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
        modified:   themes/mainroad (modified content, untracked content)

no changes added to commit
  • 위 에러가 발생이 되면, 안된다. 즉, 무언가 제대로 삭제가 되지 않았다는 뜻이며, 폴더가 없음에도 위와 같은 에러가 발생이 되면 그 때는 아래 명령어를 추가하도록 한다.
$ git rm -r --cached themes/mainroad
  • 이 때, 중요한 것은, 삭제 후, git push 까지 진행해야 한다.
$ rm -rf public
$ rm -rf themes/your_theme
$ git add .
$ git commit -m "your commit msg"
$ git push origin master(or main)
  • 이제부터가 중요하다. 순서를 지키도록 한다.
  • 먼저, theme부터 submodule을 진행한 후, 마지막으로 public에 대한 submodule을 설정한다.
    • 코드로 보면 다음과 같다.
$ git submodule add https://github.com/developer_name/your_theme.git themes/your_theme
$ git submodule add -b master git@github.com:your_name/your_name.github.io.git public
  • 이렇게 함으로써 blog 레포안에 있는 public 디렉토리는 your_name.github.io 주소와 연동이 끝나게 되는 것이다.

주의점

  • 필자의 경우, themes/my_theme안에 shortcodecss 코드 등을 추가하였다. 따라서, 이 코드 등도 당연히 추가가 되어야 한다.
    • 이 때에는 복사 붙여넣기로 대체 하도록 한다.

상황 2. ssh keygen의 필요성

  • 필자는 새로운 맥에어 m1을 구입하였기 때문에, SSH Key값을 만들어야 한다.
  • 검색을 통해서 쉽게 구할 수 있기 때문에, 자세한 내용은 메뉴얼을 참고한다. +
  • 코드로 구현하면 아래와 같다.
$ cd ~/.ssh
$ ssh-keygen -t ed25519 -C "your_email@example.com"
> Generating public/private ed25519 key pair.
> Enter a file in which to save the key (/Users/you/.ssh/id_ed25519): [Press enter]
> Enter passphrase (empty for no passphrase): [Type a passphrase]
> Enter same passphrase again: [Type passphrase again]
$ cat ~/.ssh/id_ras.pub
  • 이때, 출력값 전체(이메일 포함)하여 복사 한후, 깃허브 계정에서 [Settings]-[SSH and GPG Keys]-[New SSH Key]를 클릭하며 붙여 넣기 한 후 저장한다.
  • 그런데, 하나 주의해야 하는 것은, 이대로 끝내면, 블로그를 업데이트 할 때마다, 계속 비밀버호를 입력하라고 한다. 매우 귀찮기 때문에, 아래와 같은 코드를 실행한다.
$ ssh-add ~/.ssh/id_rsa
$ eval $(ssh-agent)

상황 3. 버전 문제

  • 모두에게 해당 사항이 안될 수도 있다.
    • 현재 필자가 겪는 에러이다.
$ WARN 2020/10/12 13:40:31 Failed to get translated string for language "en" and ID "authorbox_name": template: :1:9: executing "" at <.Count>: can't evaluate field Count in type string

블로그 옮기기 성공

  • 이 글을 보고 있다면, m1에서 처음 작성하여 성공적으로 올린 글을 보게 되는 것이다.
  • 즉, 필자는 성공하였다.
    • hugo의 가장 큰 어려움은 사실 한글자료가 많지 않다.
    • 이 글을 보는 hugo 사용자에게 작은 도움이 되기를 바란다.

Hugo - 이미지 위치 설정

I. Problem

Hugo에서 이미지를 업로드하면 자동적으로 왼쪽(Left) 정렬이 된다. 기본적으로 마크다운 내에서 html 적용은 되지 않는 문제점이 있다.

  • 아래는 기본적인 img 업로드 방식이다.
![](/img/programming/2020/05/numpy_array_creation/numpy.png)

  • 위 그림처럼 왼쪽으로 치우친 것을 볼 수 있다. 이럴 경우 어떻게 해결해야 할까? 간단하게 해결 방법을 정리하여 공유한다.

II. CSS 파일 찾기

  • 기본적으로 이미지를 핸들링 하는 것은 CSS 파일에서 해결한다. 문제는 어떤 CSS 파일을 열어야 하는지 처음에는 어려울 것이다.
  • 첫째, 대부분 hugo 개발자들이 테마를 사용하기 때문에 테마에서 css 파일을 찾는다.
    • 강사의 테마는 mainroad이며, 위 기준으로 말씀드리면 파일 경로는 아래와 .
themes/mainroad/assets/css/style.css
  • style.css 파일을 열면, 테마에 적용된 각종 css 태그들을 확인할 수 있다.

III. CSS 파일에 소스 추가

  • 다른 소스 코드는 만지지 않는다.
  • 맨 마지막에서 아래와 같은 소스코드를 입력한다.
img[src$='#center']
{
    display: block;
    margin: 0.7rem auto; /* you can replace the vertical '0.7rem' by
                            whatever floats your boat, but keep the
                            horizontal 'auto' for this to work */
    /* whatever else styles you fancy here */
}

img[src$='#floatleft']
{
    float:left;
    margin: 0.7rem;      /* this margin is totally up to you */
    /* whatever else styles you fancy here */
}

img[src$='#floatright']
{
    float:right;
    margin: 0.7rem;      /* this margin is totally up to you */
    /* whatever else styles you fancy here */
}
  • 위 코드에서 각 스타일에 맞게 margin, float 등을 css 코드에 맞게 수정 변환하면 된다.
  • 수정하였다면 이제 저장한뒤, 작성중인 마크다운으로 다시 돌아간다.

IV. Markdown 파일에의 적용.

  • 이제 적용해보자. 적용하는 것은 어렵지 않다. 이미지 경로 마지막에 #center, #floatleft, #floatright 등을 입력하면 된다.
![](/img/programming/2020/05/image_center/your_image.png#center) # floatleft, floatright
  • #center의 예시

Hugo + Mathjax 설정

I. 인라인 수식 에러

한동안 수식 에러를 많나 고생하였다. $$ ... $$ 코드는 잘 적용이 되었다. 그런데, 글 중간에 수식을 넣는 건 잘 되지 않았다. $ ... $ 표현하면 수식문법이 그대로 나와서 글의 가독성이 조금 떨어져 있었다. 통계수식을 넣어주면, 그냥 무언가 전문가스럽다! 전문가도 아니지만 ㅎㅎ

  • $x_{i}$ 내가 표현하고자 하는 것 Vs. x_{i} 실제로 화면에 나오는 것

그리고, 한동안 헤매었다. 길은 알고 있었으나, 역시 적용이 쉽지 않았다. 아래는 해결 방안을 공유한다.