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

Time:12-26

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("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>",
    })
})

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

<h1>Hello World</h1>

What I'm hoping to get is:

Hello World

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

CodePudding user response:

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

CodePudding user response:

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("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")),
   })
 })

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

  • Related