5

そのため、構造体からブール値をチェックする単純な if チェックを行っていますが、動作していないようで、HTML のレンダリングを停止するだけです。

したがって、次の構造体は次のようになります。

type Category struct {
    ImageURL      string
    Title         string
    Description   string
    isOrientRight bool
}

これで、範囲とともに表示できる Category 構造体のスライスができました。

以下は、1 つの構造体の例です。

juiceCategory := Category{
    ImageURL: "lemon.png",
    Title:    "Juices and Mixes",
    Description: `Explore our wide assortment of juices and mixes expected by
                        today's lemonade stand clientelle. Now featuring a full line of
                        organic juices that are guaranteed to be obtained from trees that
                        have never been treated with pesticides or artificial
                        fertilizers.`,
    isOrientRight: true,
}

以下のように複数の方法を試しましたが、どれもうまくいきませんでした。

{{range .Categories}}
    {{if .isOrientRight}}
       Hello
    {{end}}
    {{if eq .isOrientRight true}}
       Hello
    {{end}}

   <!-- Print nothing -->
   {{ printf .isOrientRight }} 

{{end}}
4

2 に答える 2

8

テンプレートからアクセスしたいすべてのフィールドをエクスポートする必要があります: 最初の文字を大文字に変更しますI:

type Category struct {
    ImageURL      string
    Title         string
    Description   string
    IsOrientRight bool
}

そしてそれへのすべての参照:

{{range .Categories}}
    {{if .IsOrientRight}}
       Hello
    {{end}}
    {{if eq .IsOrientRight true}}
       Hello
    {{end}}

   <!-- Print nothing -->
   {{ printf .IsOrientRight }} 

{{end}}

エクスポートされていないすべてのフィールドには、宣言パッケージからのみアクセスできます。パッケージはCategoryタイプを宣言し、text/templatehtml/templateは異なるパッケージであるため、これらのパッケージにアクセスできるようにする場合は、エクスポートする必要があります。

Template.Execute()はエラーを返します。その戻り値を保存/調べた場合、次のようなエラーが発生するため、すぐにこれを見つけることができます。

テンプレート: :2:9: <.isOrientRight> で "" を実行しています: isOrientRight は構造体型 main.Category のエクスポートされていないフィールドです

Go Playgroundでコードの実際の例を参照してください。

于 2016-11-08T19:42:05.397 に答える