zoukankan      html  css  js  c++  java
  • Gin框架静态文件处理

    Gin框架静态文件处理

    一、静态文件处理

    当我们渲染的HTML文件中引用了静态文件时,我们只需要按照以下方式在渲染页面前调用gin.Static方法即可。

    func main() {
    	r := gin.Default()
    	r.Static("/static", "./static")
    	r.LoadHTMLGlob("templates/**/*")
       // ...
    	r.Run(":8080")
    }
    
    package main
    
    import (
    	"github.com/gin-gonic/gin"
    	"net/http"
    )
    
    func main() {
    	r := gin.Default()
    	// 加载静态文件
    	r.Static("/css", "../statics")
    
    	r.LoadHTMLFiles("../templates/index.tmpl")
    
    	r.GET("/index/css", func(c *gin.Context) {
    		c.HTML(http.StatusOK, "index.tmpl", gin.H{
    			// H is a shortcut for map[string]interface{}
    			//type H map[string]interface{}
    			// 渲染模板
    			"title": "gin渲染模板",
    		})
    	})
    
    	r.Run(":9999")
    }
    
    

    模板

    # index.css
    body{
        background-color: #ff002f;
    }
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        {{/*    引用css静态文件*/}}
        <link rel="stylesheet" href="/css/index.css">
        <title>users/index</title>
    </head>
    <body>
    {{.title}}
    </body>
    </html>
    
    

    image-20211115222531000

    image-20211115223150948

    二、script文件处理

    package main
    
    import (
    	"github.com/gin-gonic/gin"
    	"net/http"
    )
    
    func main() {
    	r := gin.Default()
    	// 加载静态文件
    	r.Static("/css", "../statics")
    
    	r.LoadHTMLFiles("../templates/index.tmpl")
    
    	r.GET("/index/css", func(c *gin.Context) {
    		c.HTML(http.StatusOK, "index.tmpl", gin.H{
    			// H is a shortcut for map[string]interface{}
    			//type H map[string]interface{}
    			// 渲染模板
    			"title": "gin渲染模板",
    		})
    	})
    
    	r.Run(":9999")
    }
    
    

    模板

    // index.js文件
    alert("js渲染")
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        {{/*    引用css静态文件*/}}
        <link rel="stylesheet" href="/css/index.css">
        <title>users/index</title>
    </head>
    <body>
    {{.title}}
    <script src="/css/index.js"></script>
    </body>
    </html>
    
    

    image-20211115223344428

    https://sc.chinaz.com/

  • 相关阅读:
    mysql单个表内去重多个重复的字段
    scrapy xpath有空格处理
    有道选择语言性翻译
    豆瓣源
    scrapy 编码
    西祠代理获取
    有道翻译
    远程连接服务器for Linux
    ECshop通过文章分类的ID实现不同模板
    创建WordPress管理员账号
  • 原文地址:https://www.cnblogs.com/randysun/p/15626549.html
Copyright © 2011-2022 走看看