martini-contrib / render Goto Github PK
View Code? Open in Web Editor NEWMartini middleware/handler for easily rendering serialized JSON, XML, and HTML template responses.
License: MIT License
Martini middleware/handler for easily rendering serialized JSON, XML, and HTML template responses.
License: MIT License
my english is poor,sorry!
I just want to do this,in layout
<html>
....
{{yield}}
.....
{{res}}
<html>
now,I have a index file named index.html.in the same dir,i have an other file name index.html.res.
I want the index.html into the yield,and the index.html.res to the {{res}}
this is the dir like.
-----view
----------layout
---------------default.tmpl
----------xxx_dir
---------------xxx.html
---------------xxx.html.res
-----index.html
-----index.html.res
every res file content is different.How to do it?
I try to do it with Funcs,but i cant get the .res file path.
engine.Use(render.Renderer(render.Options{
// Specify what path to load the templates from.
Directory: conf.AppDir.View,
// Specify a layout template. Layouts can call {{ yield }} to render the current template.
Layout: "layout/default",
// Specify extensions to load for templates.
Extensions: []string{".tmpl", ".html"},
// Specify helper function maps for templates to access.
Funcs: []template.FuncMap{{
"res":func(args ...interface{}) template.HTML {
// here i cant get the .res path
return template.HTML(s)
},
}},
// Sets delimiters to the specified strings.
Delims: render.Delims{"{{", "}}"},
// Sets encoding for json and html content-types. Default is "UTF-8".
Charset: "UTF-8",
// Output human readable JSON
IndentJSON: true,
}))
Hi,
When using and a layout+yield
, is there a way to know which layout will be (or was) yield ?
I'm thinking about a classic layout with bootstrap navbar. It could be nice to know which template is yield
to be able to activate the right button.
Would you be interested by a PR ?
I think it would be right if HTMLContentType was defined in HTMLOptions instead of Options.
I am setting my static folder to assets
, but martini is giving me a 404 error
[martini] Started GET /assets/css/main.css for [::1]:52990
[martini] Completed 404 Not Found in 325.927µs
directory structure
assets/
|
|__ css/
|__ main.css
templates/
|
|__index.tmpl
|__layout.tmpl
main.go
main.go
package main
import (
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
)
func main() {
m := martini.Classic()
m.Use(render.Renderer(render.Options{
Layout: "layout",
}))
m.Use(martini.Static("assets"))
m.Get("/", func(r render.Render) {
r.HTML(200, "index", nil)
})
m.Run()
}
layout.tmpl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="assets/css/main.css">
</head>
<body>
{{yield}}
</body>
</html>
Hi,
As I understand, according to the documentation, the layout is set during the project initialization.
How could I change the layout for the certain action?
Or I should simply
m.Get("/", func(r render.Render) {
r.Layout = "new-layout"
r.HTML(200, "hello", "jeremy")
})
??
Thanks
I get the error "Value not found for type render.Render"
if I import using
"github.com/martini-contrib/render",
while I don't get it upon using
"github.com/codegangsta/martini-contrib/render"
I notice that the files in "github.com/codegangsta/martini-contrib/render" are rather old (not having render.Header(), etc.) and hence I want to use the files from this repository, but I'm getting the error upon using the files here.
I'm using the render to send back json entities.
It's working fine, but I would like to remove some fields from the response. For example, I don't want to send the user password back to the client.
Is there any option to do this?
Is there any way to do rails-way content_for thing? When you could do like {{yield .Foo}} in layout, while somewhere in views, create this .Foo object, so it'd render in some specific part in layout?
This is my code:
location := Place{}
location.region , location.city = getLocation(params["code"])
r.HTML(200, "home/place", location)
When i code : {{.}} , then it shows {abc def }
But I wanna show somethings like:
My region: {{ .region }}
My city : {{ .city }}
But i can't. So, can you show me how to do that ? Thank you
Excuse me,
when web application have one more layout,how render.Options set the value?
Is there an example I can look at to see how Renderer handles multiple layouts? Say my registration page and my login page have two different layouts. How would I handle that?
From this code:
m.Use(render.Renderer(render.Options{
Layout: "layout",
}))
It seems that you can only have one layout per Renderer. Would I "use" multiple Renderers?
Thanks.
Hi,
I've got some javascript in my layout.html :
UserName = ""
$(document).ready(function(){
if(UserName != ""){
$("#menu").removeClass("hidde");
$("#menu").addClass("reveal");
}
});
UserName is a global variable that i set in an another html file :
function Login(){
var log = $("#login").val();
var mdp = $("#mdp").val();
var sended = {
url: '{{.LoginUrl}}',
type: 'POST',
data: {'\"log\"': log, '\"mdp\"': mdp},
success: function(data){
if(data.Success){
UserName = data.UserName;
window.location.replace(data.Url);
}
else{
alert(data.Err);
}
}
};
$.ajax(sended);
}
I've check the data returned and my UserName is ok with the json return so must be the assignation.
But when i do the redirection UserName go back to "" and i can't use it.
Is it because the layout is reloaded every time i have a navigation?
Thanks for reading and i hope you can help me.
As much as I dislike it, I'm stuck spitting out XML for a certain part of a service I'm working on. Are there any plans add a render XML method? If not, would a pull request be accepted if I were to write one up?
Thanks for the great tool!
I am trying to define code blocks that will get injected in the base template if they are defined. I don't want to include all the scripts that are required on one page onto another that doesn't require it.
Basically what im trying to do is something like:
on the layout: admin.tmpl
:
<script src="jquery.min.js"></script>
<script src="scripts.min.js"></script>
{{ footer_extra }}
and on new.tmpl
:
{{define "footer_extra"}}
<!-- scripts just for this page -->
<script src="script-1.js"></script>
<script src="script-2.js"></script>
<script src="script-3.js"></script>
{{end}}
Not sure if this is something i could just achieve with Go, kinda new to the language.
Thanks!
Hi is this possible?
Alternatively, how can I include another view from within a view?
It would be cool to support jade
. It is originating from nodejs, but its also a compiler that can be used on the command line.. Having an 'engine' that could be configured to compile a view when it is requested (then cached) would be really helpful.
What do you think?
I use render to generate some basic HTML and I don't manage to create a relative URL to the current route without hardcoding all the URL.
For example I create a group "admin" and in the template I would like to create link without having to repeat "/admin" in the templates.
How to use template define with this package?
I want to create some template helpers, but not sure how to call helper functions from template. Is there way to do this?
I believe that the convention is to present the default values when listing available configuration keys in various docs and README files. The values presented in the Options section of the README are inconsistent with the defaults defined in the source code. Example:
Extensions: []string{".tmpl", ".html"},
but the source code defaults to
opt.Extensions = []string{".tmpl"}
That might be confusing as for example I assumed that the configuration presented in the README is consistent with the default one and couldn't figure out why my .html
templates are not being loaded.
I'm trying to set the 'Access-Control-Allow-Origin
header - how should I go about doing this with Render?
Unless I'm missing something, the addYield method leaks memory.
func (r *renderer) addYield(name string, binding interface{}) {
funcs := template.FuncMap{
"yield": func() (template.HTML, error) {
buf, err := r.execute(name, binding)
// return safe html here since we are rendering our own template
return template.HTML(buf.String()), err
},
"current": func() (string, error) {
return name, nil
},
}
r.t.Funcs(funcs)
}
r.execute method Gets a buffer from the buffer pool, but the buffer is never Put back to the pool. I suggest getting rid of the r.execute method (it's two lines of code) and essentially in-lining its functionality. Doing so will allow deferring the buffer Put immediately after the the buffer Get. Seeing these paired together makes it much easier to ensure the buffer is returned.
from @ahall
The goal is to be able to do something like this:
m.Use(render.Renderer(render.Options{
Layout: "layout",
Funcs: []template.FuncMap{
{
"myCustomFunc": func(r *http.Request, m MyInjectedStuff) string {
// Do something with r and m
return "My custom function"
},
},
},
}))
Original issue:
https://github.com/codegangsta/martini-contrib/issues/99
./main.go:35: missing return at end of function
m.Get("/test", func (r render.Render) string {
r.HTML(200, "index", "world")
})
I can't seem to figure out the problem here, any ideas?
I use:
render.Renderer(render.Options{Directory: "views", Layout: "layout", Extensions: []string{".go.html",".html"}})
files in dir views:
layout.go.html
hello.go.html
http output:
html/template: "layout" is undefined
if I rename files and remove .go then all ok
Hi,
after seeing go-martini/martini@6779472 i tried to build menus based on the active route. I sucessfully used the approach suggested in #3 for some other helpers and now tried to inject the current Route but I get a "Value not found" panic. I posted a small example here.
ps: i wasn't sure if i should post this on this repo or go-martini, because i couldn't make sense of the stacktrace and don't know if this issue is directly related to render but i guess so because i can use the injected route in normal request handlers.
when was in develop mode, the template always changes, can add dev mode to render?
Maybe this is already possible, and I just don't know how to do it. I would like to be able to define different extensible areas in my layout. I'm thinking of something similar to Jade's named blocks.
<!-- templates/layout.tmpl -->
<body>
<div class="container">
{{ yield content }}
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
{{ yield javascripts }}
</body>
So here I've defined 2 different sections that can be extended, content
and javascripts
. In my template I would want to be able to extend each of those areas.
{{ extends content }}
<h1>Hello World</h1>
<span id="blah"></span>
{{ end }}
{{ extends javascripts }}
<script type="text/javascript">
$("#id").text("Hello from Javascript");
</script>
{{ end }}
The syntax here is obviously theoretical. I'm new to Go, so maybe this is somehow already possible, or maybe I'm thinking about the problem wrong. If so, feel free to set me straight.
Any plans on adding support for other template engines like Mustache (https://github.com/hoisie/mustache) or Amber (https://github.com/eknkc/amber)?
I discovered this while trying to implement a cache handler. We don't want to cache all of our requests, so we'd like to pass the cache handler to the router. In order to do this, however, Renderer has to be passed to every route as well and after the cache.
Example:
martiniServer.Use(render.Renderer())
router := martini.NewRouter()
// Caching won't work here because it wants to intercept and
// and replace the http.ResponseWriter, but Render has a
// reference to the original ResponseWriter. The replaced one
// will never be used.
router.Get("/", cache, func(r render.Render) {
r.HTML(200, "index", "Welcome")
}
Is it necessary to capture the ResponseWriter? Is there a better way to do what I'm trying to do?
Original conversation:
https://github.com/codegangsta/martini-contrib/issues/96
Hi,
I am very new to golang, so maybe my question is a go issue. I'm sorry if it is the case.
Anyway, I would love not to be obliged to pass a func(r render.Render)
to every route I create. It would be great to write something like this :
package main
import (
"github.com/codegangsta/martini"
"github.com/martini-contrib/render"
"net/http"
)
func hello(params martini.Params, writer http.ResponseWriter, renderer *render.Render) string {
return renderer.HTML(200, "mytemplate", nil)
}
func main() {
m := martini.Classic()
m.Use(render.Renderer())
m.Get("/", hello)
m.Run()
}
but I have the following error :
./server.go:10: renderer.HTML undefined (type *render.Render has no field or method HTML)
Is that possible ?
I read something similar with the mgo
package where the author created a mongo middleware : http://progadventure.blogspot.fr/2014/03/learning-go-with-martini-working-with.html
Thanks
when web application have more templates,how handle redefinition error?
go build app.go, error:
panic: template: redefinition of template "head"
if delete {{define "head"}} ... {{end}} else
panic: template: redefinition of template "body".
file home.tmpl code:
{{template "base.tmpl" .}}
{{define "head"}}<title>mytest -- home page</title>{{end}}
{{define "body"}}
<a href="/">home</a>
<a href="/test">test</a>
{{end}}
file test.tmpl code:
{{template "base.tmpl" .}}
{{define "head"}}<title>mytest -- test page</title>{{end}}
{{define "body"}}
<a href="/">home</a>
<a href="/test">test</a>
{{end}}
file base.tmpl code:
<!DOCTYPE html>
<html>
<head>
{{template "head" .}}
</head>
<body>
<div id="wrapper">
<div id="main" class="container">
{{template "body" .}}
</div>
</div>
</body>
</html>
I'd like to have on my templates
directory Markdown files which could be rendered as html code. Is this possible? Os should I use some tool like Blackfriday by my own?
Is there a way to add a function map within a controller? I want to keep my logic seperated so that I am not exposing models in main.go and I want to be able to evaluate things on the template itself. It currently panics by saying the function map I want to introduce isn't defined, but how do I declare it without putting it on main.go and keeping it specific to the controller? Consider the code snippets below:
import(
"../controllers/blog"
)
func main(){
m := martini.Classic()
...
m.Get("/blog, blogCtlr.Index")
...
m.Run()
}
m.Get("/blog", blogCtlr.Index)
FuncMap["showPostsLink"] = func (c blog.Category) bool{
return len(c.Posts) > 0 && c.Active
}
import(
"github.com/martini-contrib/render"
"github.com/martini-contrib/web"
"net/http"
"../models/blog"
)
func Index(ctx *web.Context, r.Render){
categories, err := blog.GetAllCategories()
if err != nil{
ctx.Abort(http.StatusInternalServerError, err.Error())
return
}
data := struct{
Categories : categories,
}
r.HTML(200, "blog", data)
return
}
<div class="categories">
{{range $c := .Categories}}
<div class="category">
<div class="categoryname">$c.Name</div>
{{if showPostsLink $c}}
<a class="btn btn-default" href="/blog/showposts/$c.Id">Show Posts</a>
{{end}}
</div>
{{end}}
</div>
Thanks for any and all help anyone is able to provide!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.