如何使用Gin框架内置的模板引擎渲染从数据库中检索到的HTML呢?

huangapple go评论67阅读模式
英文:

How to render HTML retrived from DB, using Gin Framwork built in Template engine?

问题

有点超出我的能力范围了,而且我也找不到适合我使用情况的解决方案。

我目前正在处理一个项目,在某些情况下,当用户访问某个页面"使用Gin框架模板"时,页面的一部分内容是通过从数据库检索的数据进行渲染的。

这种方法的问题在于,Gin似乎没有提供允许我渲染任何内容而不完全转义的能力。

我之前使用过"PHP框架"进行开发,并使用了它的模板引擎"Balde"。如果需要,我可以直接渲染HTML而不进行转义,只需使用以下指令"{!! $variableName !!}"。

但是在使用Gin时,我没有成功找到任何内置的模板指令,可以让我直接从数据库中渲染检索到的HTML内容。

希望有人能够支持、提供解决方案或指导如何解决这个问题。

以下是一个示例和我得到的结果以及我希望得到的结果。

以下是我目前问题的一个快速示例:

router := gin.Default()

router.LoadHTMLGlob("templates/*")

router.GET("/", func(c *gin.Context) {
	db, err := gorm.Open(mysql.Open(configs.DB_Connection()), &gorm.Config{})

	if err != nil {
	   panic("failed to connect database")
	}

	c.HTML(http.StatusOK, "index.html", gin.H{
		"title": "<h1>Hello World</h1>",
	})
})

使用Gin中的内置模板引擎,我得到以下结果:

&lt;h1&gt;Hello World&lt;/h1&gt;

我希望得到的是:

Hello World

请注意,我直接从数据库获取到的是HTML内容。

英文:

A bit over my head here, and the for the life me I could not find suitable solution to my usage case scenario.

I'm currently working on a project where in some scenario, when a user visit a certain page "Using Gin Framework Templates", part of the page content is rendered via data retrieved from the DB.

The issue with this approach is that Gin dose not seam to provide the ability to allow me to render any content Without fully escaping it.

I have developed previously with "PHP Framework", and used its template engine "Balde" I was able to if the need arises-ed to have the option to render HTML directly without escaping by using the following Directive "{!! $variableName !!}".

But in Using Gin, I was not successful into finding any builtin template directive that would allow me to render retrieved HTML content directly from DB.

Hope if anyone could support or provide solution or direction on how to solve this issue.

The following is a could sample and which results I get and which results I hope to get.

The following is a quick example of my current issue:

router := gin.Default()

router.LoadHTMLGlob(&quot;templates/*&quot;)

router.GET(&quot;/&quot;, func(c *gin.Context) {
	db, err := gorm.Open(mysql.Open(configs.DB_Connection()), &amp;gorm.Config{})

	if err != nil {
	   panic(&quot;failed to connect database&quot;)
	}

	c.HTML(http.StatusOK, &quot;index.html&quot;, gin.H{
		&quot;title&quot;: &quot;&lt;h1&gt;Hello World&lt;/h1&gt;&quot;,
	})
})

Using the builtin template engine in Gin, I get the following results:

&lt;h1&gt;Hello World&lt;/h1&gt;

What I'm hoping to get is:

Hello World

Please note that I'm getting that HTML directly from the DB.

答案1

得分: 2

我已经找到了一个解决方案,适用于我的使用案例场景,基于以下线程和我自己对其进行的调整,以使其与GORM一起工作。

解决方案如下:

创建以下函数:

func getStructFeild(v *migrations.TableName, field string) string {
    r := reflect.ValueOf(v)
    f := reflect.Indirect(r).FieldByName(field).String()
    return f
}

然后使用以下代码:

router := gin.Default()

router.LoadHTMLGlob("templates/*")

router.GET("/", func(c *gin.Context) {
    db, err := gorm.Open(mysql.Open(configs.DB_Connection()), &gorm.Config{})

    if err != nil {
        panic("failed to connect database")
    }

    var table migrations.TableName
    db.Where("id = ?", 1).Select("column_name").Find(&table)

    c.HTML(http.StatusOK, "index.html", gin.H{
        "title": template.HTML(getStructFeild(&table, "ModalStructColumnName")),
    })
})

这样,Gin模板就能够完全渲染从数据库中检索到的HTML了。

英文:

I have managed to find a solution to my use case scenario, based on the following Thread , and my own adjustments to make work with GORM as well.

Solution is:

create the following function:

func getStructFeild(v *migrations.TableName, field string) string {
     r := reflect.ValueOf(v)
    f := reflect.Indirect(r).FieldByName(field).String()
    return f
}


router := gin.Default()

router.LoadHTMLGlob(&quot;templates/*&quot;)

router.GET(&quot;/&quot;, func(c *gin.Context) {
  db, err := gorm.Open(mysql.Open(configs.DB_Connection()), &amp;gorm.Config{})

  if err != nil {
     panic(&quot;failed to connect database&quot;)
  }

	var table migrations.TableName
	db.Where(&quot;id = ?&quot;, 1).Select(&quot;column_name&quot;).Find(&amp;table)

   c.HTML(http.StatusOK, &quot;index.html&quot;, gin.H{
     &quot;title&quot;: template.HTML(getStructFeild(&amp;table, &quot;ModalStructColumnName&quot;)),
   })
 })

and that's it Gin Template is now able fully render the HTML that is retrieved from the DB.

答案2

得分: 0

Go语言内置了一个用于渲染HTML模板的库html/template,但它的语法可能与其他模板引擎(如Blade、Mustache)有些不同。

英文:

Go has a builtin library for rendering html template but it's syntax might be a little different then others like blade, mustache.

huangapple
  • 本文由 发表于 2022年12月26日 16:00:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/74918329.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定