ViewModel

The ViewModel is a conceptual type that you will use often while working with torque, as it represents how you'll turn raw response data into fully featured web pages.

Terms

Model: This is the underlying data or the structure of information you want to present.

View: The visual or structured way this data is presented to users, such as HTML, JSON, or XML.

Rendering: The process of taking data from the model and transforming it into a view.

In Practice

In an actual torque application, a ViewModel is a Go struct that holds the data needed to render a view.

For example, a blog post ViewModel might look something like this:

The ViewModel is associated one-to-one with a Controller, as the Controller loads the ViewModel and renders it to an HTTP response.

The ViewModel is used as the generic constraint when building a Handler using the New function.

This constraint is passed along to any of the Controller API interfaces implemented by the given Controller.

Loading

ViewModels are loaded during an HTTP GET request.

The generic constraint T in the Loader interface corresponds to your ViewModel type.

Rendering

In response to an HTTP request, a ViewModels can be rendered into many formats depending on the interfaces it implements and the request's Accept header.

By default, torque will render your data into json format. To change this, you have some options:

HTML Templates

Associate your ViewModel with a Go template by implementing the TemplateProvider interface. Read more about templates and the tmpl compiler.

Custom Renderer

Implement a custom Renderer to write your data in other formats such as XML or plaintext.