LoginSignup
1
0

More than 5 years have passed since last update.

text/templateを用いた際の文字列の色付け

Posted at

https://github.com/x-color/tdl を作成時にtext/templateを用いてターミナル上に出力する際に、色付けしようとして詰まったので、その解決策のメモを残す。

何がしたかったのか

text/templateを用いた際に、文字列に色を付けてターミナル上に出力したい。

colored text image

改善前

色付けするカラーコードを追加しtext/templateを用いてターミナル上に出力するコード。

template.go
package main

import (
    "os"
    "text/template"
)

func main() {
    temp := `\x1b[1m\x1b[32mColored\x1b[0m`
    t := template.Must(template.New("colored text").Parse(temp))
    t.Execute(os.Stdout, nil)
}

このコードは実行すると

non colored text image

のようになり色付けされない。

改善後

変更点は、色付けしたい文字列とカラーコードをまとめて{{""}}で囲って出力した点。

template.go
package main

import (
    "os"
    "text/template"
)

func main() {
    temp := `{{"\x1b[1m\x1b[32mColored\x1b[0m"}}` // ここを修正した
    t := template.Must(template.New("colored text").Parse(temp))
    t.Execute(os.Stdout, nil)
}

このコードは実行すると

colored text image

のようになりしっかりと色付けされる。

おまけ

text/templateを用いて{{, }}を出力したい場合も{{""}}で囲うことで出力することができる。

参考 https://stackoverflow.com/questions/17641887/how-do-i-escape-and-delimiters-in-go-templates

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0