英文:
Martini routes with named parameter fails static files loading
问题
我用Martini编写了我的第一个Go应用程序。我有一个带有命名参数的路由:
m := martini.Classic()
staticOptions := martini.StaticOptions{Prefix: "assets"}
m.Use(martini.Static("assets", staticOptions))
m.Get("/edit/:id", editHandler)
m.Run()
editHandler渲染带有bootstrap样式表和位于assets/css
和assets/js
文件夹中的脚本的编辑模板。
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css">
<script type="text/javascript" src="assets/js/bootstrap.min.js"></script>
但是当我在浏览器中打开编辑页面时,我的静态文件不加载,因为浏览器发送请求到edit/assets/css/bootstrap.min.css
和edit/assets/js/bootstrap.min.js
。我该如何去掉任何路由前缀(如'edit'、'show'和其他)?
英文:
I wrote my first Go application with Martini. I have route with named parameter:
m := martini.Classic()
staticOptions := martini.StaticOptions{Prefix: "assets"}
m.Use(martini.Static("assets", staticOptions))
m.Get("/edit/:id", editHandler)
m.Run()
The editHandler renders edit template with bootstrap stylesheet and script which lie in assets/css
and assets/js
folders accordingly.
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css">
<script type="text/javascript" src="assets/js/bootstrap.min.js"></script>
But when I open edit page in my browser my static files don't load, because browser makes requests to edit/assets/css/bootstrap.min.css
and edit/assets/js/bootstrap.min.js
.
How can I strip any route prefix?('edit', 'show' and others)
答案1
得分: 3
你提供的 HTML 代码片段中的链接是相对链接。这意味着当浏览器解析 URL 时,它会将给定的路径附加到当前主机和路径上,例如 http://<hostname_and_port>/edit + assets/css/bootstrap.min.css
。
你可以使用根路径而不是相对路径,以确保当浏览器解析 URL 时,它将给定的路径附加到主机的根路径上,而不管完整的 URL 路径是什么。这可以通过在路径的开头加上斜杠来实现。在下面的示例中,我在 src
和 href
属性路径中添加了一个斜杠。
<link rel="stylesheet" type="text/css" href="/assets/css/bootstrap.min.css">
<script type="text/javascript" src="/assets/js/bootstrap.min.js"></script>
英文:
The links in your supplied html snippet are relative links. This means that when the browser resolves the URL it appends the given path to the current host and path ie, http://<hostname_and_port>/edit + assets/css/bootstrap.min.css
.
You can use a root path instead of a relative path to ensure that when the browser resolves urls it appends the given path to the root of the host no matter what the full URL path is. This is done by putting a forward slash at the beginning of your path. In the following example I have added a forward slash to the src
and href
attribute paths.
<link rel="stylesheet" type="text/css" href="/assets/css/bootstrap.min.css">
<script type="text/javascript" src="/assets/js/bootstrap.min.js"></script>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论