2016-04-03 49 views
7

私はGolangをバックエンドで使用しています。 html/htmlを使用してHTMLをレンダリングすると、URLのためにZgotmplZが得られます。Golangのhtml/templateからZgotmplZを取り除くには?

{{if .UserData.GitURL}} 
<li> 
    <a href="{{.UserData.GitURL}}"> 
    <i class="icon fa fa-github"></i> 
    </a> 
</li> 
{{end}} 

私はサーバー側でGitURLの文字列を使用しています。このURLはhttpsです。私が解決策を探すとき、ブログにはsafeURLを使用するように提案されました。だから私は試しました

{{if .UserData.GitURL}} 
<li> 
    <a href="{{.UserData.GitURL | safeURL}}"> 
    <i class="icon fa fa-github"></i> 
    </a> 
</li> 
{{end}} 

しかし、コードはコンパイルされませんでした。

誰かが私にこれを手伝ってもらえますか?どんな提案も本当に役に立ちます。

+0

URL文字列が正しいことを確認してください。たとえば、 'https:'の代わりに 'https:'の代わりに 'https: 'が表示されている場合、' ZgotmplZ 'を出力します。 –

+3

[HTMLテンプレートの出力にZgotmplZが表示されるのはなぜですか?](https:// stackoverflow .com/questions/14765395/why-am-i-seeing-zgotmplz-in-my-go-html-template-output) – Carpetsmoker

答えて

6

ZgotmplZは入力が無効であることを示す特別な値です。 html/templateのドキュメントからの引用:

"ZgotmplZ" is a special value that indicates that unsafe content reached a 
CSS or URL context at runtime. The output of the example will be 
    <img src="#ZgotmplZ"> 
If the data comes from a trusted source, use content types to exempt it 
from filtering: URL(`javascript:...`). 

あなたは有効な URLテキストを代用したい場合は、safeURL機能などのような特別なものは必要ありません。テンプレートの実行結果が"#ZgotmplZ"の場合、挿入するURLが無効であることを意味します。

は、この例を参照してください:

t := template.Must(template.New("").Parse(`<a href="{{.}}"></a>` + "\n")) 
t.Execute(os.Stdout, "http://google.com") 
t.Execute(os.Stdout, "badhttp://google.com") 

は出力:

<a href="http://google.com"></a> 
<a href="#ZgotmplZ"></a> 

あなたはエスケープせずに、そのままURLを使用する場合は、タイプtemplate.URLの値を使用することができます。この場合、指定された値は有効なURLでなくてもそのまま使用されます。

safeURLは、テンプレートで使用できる魔法や事前宣言された機能ではありません。しかし、あなたはタイプtemplate.URLの値としてstring URLパラメータを返す、独自のカスタム関数を登録することがあります。

t2 := template.Must(template.New("").Funcs(template.FuncMap{ 
    "safeURL": func(u string) template.URL { return template.URL(u) }, 
}).Parse(`<a href="{{. | safeURL}}"></a>` + "\n")) 
t2.Execute(os.Stdout, "http://google.com") 
t2.Execute(os.Stdout, "badhttp://google.com") 

出力:

<a href="http://google.com"></a> 
<a href="badhttp://google.com"></a> 

注:あなたはtemplate.URLに合格することができます場合値を直接テンプレート実行に追加する場合は、safeURL()カスタム関数を登録して使用する必要はありません。

t3 := template.Must(template.New("").Parse(`<a href="{{.}}"></a>` + "\n")) 
t3.Execute(os.Stdout, template.URL("http://google.com")) 
t3.Execute(os.Stdout, template.URL("badhttp://google.com")) 

出力:

<a href="http://google.com"></a> 
<a href="badhttp://google.com"></a> 

Go Playgroundにこれらを試してみてください。

関連する問題