Code Monkey home page Code Monkey logo

Comments (4)

unrolled avatar unrolled commented on May 20, 2024

@Code-Maverick Have you looked into this anymore, or did you find a solution that is working for you?

from render.

rtbenfield avatar rtbenfield commented on May 20, 2024

@unrolled I sort of found an approach I like. I'm using an MVC architecture with a base controller struct which I embed in my individual controllers. That base controller has a RegisterTemplate function that parses the template and puts it into a map keyed on a name that is unique to that controller. The base controller embeds Render to utilize the JSON and XML functions, but redefines HTML to use a custom variation with some similarity to the one in Render. Each of my controllers has a New function to instantiate it which registers the templates used in its actions. Then the actions call the HTML function with the template name and context object. I'm currently on parsing the templates on startup because my controllers are static with request specific dependencies injected into the actions using Gorilla Context (I'd like to change this to have my controllers instantiated on each request, but I haven't found a solution to this I like yet). The benefit to this way is I can define a layout template and a view template for each view I will need and the layout template can defined many {{ template "name" .}} placeholders which get defined like {{ defined "name" }}...{{end}} in my view template. I don't get the redefinition error since each view is parsed separately.

What do you think of this approach? I'm no Go expert, so please call out anything you would do differently.

Controller.go

// Controller is the base controller of the application
type Controller struct {
    *render.Render
    templates map[string]*template.Template
}

// Initialize defaults of Base Controller
func (c *Controller) init() {
    c.Render = render.New(render.Options{
        IsDevelopment: true,
    })
    c.templates = make(map[string]*template.Template)
}

// RegisterTemplate registers a template with the given name
func (c *Controller) RegisterTemplate(name string, filenames ...string) {
    t := template.Must(template.ParseFiles(filenames...))
    c.templates[name] = t
}

// HTML renders the specified HTML template with the specified context and status code
func (c *Controller) HTML(w http.ResponseWriter, status int, name string, context interface{}) {
    if tmpl, ok := c.templates[name]; ok {
        err := tmpl.Execute(w, 5)

        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }

        head := render.Head{
            ContentType: "text/html; charset=UTF-8",
            Status:      status,
        }

        head.Write(w)
    } else {
        http.Error(w, "Template with name "+name+" not found", http.StatusInternalServerError)
    }
}

DashboardController.go

// DashboardController contains actions related to the user dashboard
type DashboardController struct {
    Controller
}

// NewDashboardController initializes a new DashboardController with its default options
func NewDashboardController() *DashboardController {
    controller := &DashboardController{}
    controller.init()
    controller.RegisterTemplate("dashboard", "templates/_authorizedLayout.gohtml", "templates/dashboard/dashboard.gohtml")
    return controller
}

// GetDashboard is a GET Action displaying the login page in HTML
func (c *DashboardController) GetDashboard(w http.ResponseWriter, r *http.Request, vars map[string]string) error {
    c.HTML(w, http.StatusOK, "dashboard", nil)
    return nil
}

from render.

unrolled avatar unrolled commented on May 20, 2024

To be honest, I don't do much templating in Go... more apis and cli apps for me. With that said, this seems alright to me. Is this issue still valid, or shall we close it?

from render.

rtbenfield avatar rtbenfield commented on May 20, 2024

Sounds good. Thanks for your work on this project.

from render.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.