feat: add templates

This commit is contained in:
log101 2024-06-19 16:42:43 +03:00
parent 14e3bed6bb
commit 0bc4325102
4 changed files with 21 additions and 10 deletions

View File

@ -20,6 +20,7 @@ func InitDB() {
} }
db.AutoMigrate(&models.EmojiReaction{}) db.AutoMigrate(&models.EmojiReaction{})
db.AutoMigrate(&models.Comment{})
} }
func GetDB() *gorm.DB { func GetDB() *gorm.DB {

23
main.go
View File

@ -59,13 +59,18 @@ func main() {
postId := c.Query("postId") postId := c.Query("postId")
comments := []models.Comment{} comments := []models.Comment{}
rows := db.Where("post_id = ?", postId).Find(&comments) if postId == "" {
c.AbortWithStatus(http.StatusBadRequest)
if rows.Error != nil { return
c.HTML(http.StatusInternalServerError, "comment_form.tmpl", gin.H{"errorMessage": "error getting comments", "comments": comments})
} }
c.HTML(http.StatusOK, "comment_form.tmpl", gin.H{"errorMessage": "error getting comments", "comments": comments}) rows := db.Where("post_id = ?", postId).Find(&comments)
if rows.Error != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
c.HTML(http.StatusOK, "comments.tmpl", gin.H{"Comments": comments})
}) })
blog.POST("/comments", func(c *gin.Context) { blog.POST("/comments", func(c *gin.Context) {
@ -75,15 +80,17 @@ func main() {
username := c.PostForm("username") username := c.PostForm("username")
if postId == "" || commentBody == "" { if postId == "" || commentBody == "" {
c.HTML(http.StatusBadRequest, "comment_form.tmpl", gin.H{}) c.AbortWithStatus(http.StatusBadRequest)
return
} }
result := db.Create(&models.Comment{Body: commentBody, PostId: postId, Username: username}) result := db.Create(&models.Comment{Body: commentBody, PostId: postId, Username: username})
if result.Error != nil { if result.Error != nil {
c.HTML(http.StatusInternalServerError, "comment_form.tmpl", gin.H{}) c.AbortWithStatus(http.StatusInternalServerError)
return
} }
c.HTML(http.StatusOK, "comment_form.tmpl", gin.H{}) c.HTML(http.StatusOK, "comment.tmpl", gin.H{"Username": username, "Body": commentBody})
}) })
} }

View File

@ -2,10 +2,10 @@
<p <p
class="font-semibold pl-3 pr-2 pb-1 border-b border-x-0 border-t-0 border-gray-400 border-solid" class="font-semibold pl-3 pr-2 pb-1 border-b border-x-0 border-t-0 border-gray-400 border-solid"
> >
Arafat Candan {{ .Username }}
</p> </p>
<p class="pl-3 py-2 pr-4"> <p class="pl-3 py-2 pr-4">
Daha önce hiç bu açıdan bakmamıştım, harika bir yazı olmuş. {{ .Body }}
</p> </p>
</div> </div>

3
templates/comments.tmpl Normal file
View File

@ -0,0 +1,3 @@
{{ range .Comments }}
{{ template "comment.tmpl" . }}
{{ end }}