maze
  • Introduction
  • Getting Started
    • Quick Start
  • Guides
    • Overview
    • Installation
    • Create New App
    • Directory Structure
    • Configuration
    • Docker
    • Controllers
      • Sessions
      • Request & Response Objects
      • Halt!
      • Respond With
      • Params Validation
      • Cookies
      • Filters
      • Flash
      • Redirection
    • Views
      • View Helpers
    • Models
      • Granite
        • Granite's README
        • Migrations
        • Validations
        • Callbacks
        • Associations
        • Querying
        • Bulk Insertions
      • Crecto
        • Crecto's README
      • Jennifer
        • Jennifer Docs
        • Migrations
        • Models
    • Routing
      • Pipelines
      • Routes
    • Websockets
      • Channels
      • Sockets
      • JavaScript Client
    • Mailers
      • Deliver a new Email
  • Testing
    • System Tests
  • Deployment
    • Digital Ocean
    • Heroku
  • CLI
    • New
    • Recipes
    • Generate
    • Database
    • Watch
    • Routes
    • Exec
    • Encrypt
    • Deploy
  • Examples
    • Maze Auth
    • Crystal Debug
    • Minimal Configuration
  • Troubleshooting
  • Contributing
  • Code of Conduct
  • HAVE A QUESTION?
    • Ask on Gitter
    • Ask on StackOverflow
    • Follow on Twitter
    • Submit an issue
Powered by GitBook
On this page
  • Examples Usages
  • Responding with JSON
  • Responding with XML
  • Responding with Text
  • Responding to All
  1. Guides
  2. Controllers

Respond With

PreviousHalt!NextParams Validation

Last updated 7 years ago

If we need to render a template to html render("template.slang") works nicely. A lot of times we want to respond with json, xml, text or something else. In those cases we use respond_with.

respond_with Demo

Examples Usages

Responding with JSON

class PetController < ApplicationController
  def index
    pets = Pet.all
    respond_with { json pets.to_json }
  end
end

Responding with XML

class PetController < ApplicationController
  def index
    pets = Pet.all
    respond_with do
      xml render("index.xml.slang", layout: false)
    end
  end
end

Responding with Text

class PetController < ApplicationController
  def index
    pets = Pet.all
    respond_with{ text "hello world" }
    end
  end
end

Responding to All

Put it all together and you can respond to whatever is asked for.

class PetController < ApplicationController
  def index
    pets = Pet.all
    respond_with do
      html render("index.slang")
      json pets.to_json
      xml render("index.xml.slang", layout: false)
      text "hello world"
    end
  end
end
See video on Youtube