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/

  • 相关阅读:
    SqlServer 查看被锁的表和解除被锁的表
    Windows Server 2012 R2 或 2016 无法安装 .Net 3.5.1
    请求文件下载URL过长处理
    T4语法
    windows下 安装 rabbitMQ 及操作常用命令
    ubuntu系统启动qtceator时提示:Qt5.5.1/Tools/QtCreator/lib/qtcreator/plugins/libHelp.so: 无法加载库
    升级到VS2013常见问题
    Windowns 无法启动 Office Software Protection Platform 服务,系统找不到指定的文件
    SVN clean失败解决方法
    使用PostSharp在.NET平台上实现AOP
  • 原文地址:https://www.cnblogs.com/randysun/p/15626549.html
Copyright © 2011-2022 走看看