简体   繁体   中英

making links clickable while pushing the data into templates

I am taking inputs from user, then adding links for mentioned users and then passing the same in the template

Input: hello @ds
String after adding links -

"@<a class="tweet-url username" href="/user/ds" data-screen-name="ds" rel="nofollow">ds</a>"

Passing the above string in .Msg (using golang template) :

     <div class="panel-body" >
             <p > {{.Msg}} </p>
     </div>

Expected outcome is: Hello @ds (with clickable link on @ds) However getting everything in text format (same as input).

@<a class="tweet-url username" href="/user/ds" data-screen-name="ds" rel="nofollow">ds</a>

What am I missing?


Got a better solution. First of all I am doing htmlEscape on the input then store it in db, then while presenting adding links followed by using document.write(string) function. With this I dont have to change the template and I dont have to worry about XSS attach. Also I am also avoiding XSS scripts in my database.

Try wrapping your string ( Msg ) in template.HTML to disable the escaping that html/template does.

Example from the docs :

The template

 Hello, {{.}}! 

can be invoked with

 tmpl.Execute(out, template.HTML(`<b>World</b>`)) 

to produce

 Hello, <b>World</b>! 

instead of the

 Hello, &lt;b&gt;World&lt;b&gt;! 

that would have been produced if {{.}} was a regular string.

Note that you should do this with great care... make sure that you trust the string you're wrapping in template.HTML . This is an easy way to open yourself up to XSS attacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM