GithubHelp home page GithubHelp logo

ml-archive / flash Goto Github PK

View Code? Open in Web Editor NEW
36.0 7.0 11.0 266 KB

Flash messages between views ⚡️

License: MIT License

Swift 100.00%
swift vapor server-side-swift flash flash-messages vapor-2 vapor-3 brto

flash's Introduction

Flash ⚡️

Swift Version Vapor Version Circle CI codebeat badge codecov Readme Score GitHub license

This package allows you to display Flash messages between your views.

image

Installation

Add Flash to the package dependencies (in your Package.swift file):

dependencies: [
    ...,
    .package(url: "https://github.com/nodes-vapor/flash.git", from: "4.0.0")
]

as well as to your target (e.g. "App"):

targets: [
    ...
    .target(
        name: "App",
        dependencies: [... "Flash" ...]
    ),
    ...
]

Getting started 🚀

First make sure that you've imported Flash everywhere when needed:

import Flash

Adding the provider

public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
    try services.register(FlashProvider())
}

Adding the middleware

You can either add the Flash middleware globally by doing:

func configure(_ app: Application) throws {
    app.middleware.use(FlashMiddleware())
}

Alternatively, you can add the middleware to individual route groups where needed:

router.grouped([SessionsMiddleware(driver: app.sessions.driver), FlashMiddleware()]) { router in
    // .. routes
}

Please note that the SessionsMiddleware needs to be added to the same route groups where Flash is added.

Adding the Leaf tag

In order to render Flash messages, you will need to add the Flash Leaf tag to your application:

func configure(_ app: Application) throws {
    app.leaf.tags["flashes"] = FlashTag()
}

Using Flash messages

With Flash set up, you are now able to redirect while adding a Flash message, given a Request:

request.redirect(to: "/users").flash(.success, "Successfully saved")
request.redirect(to: "/users").flash(.info, "Email sent")
request.redirect(to: "/users").flash(.warning, "Updated user")
request.redirect(to: "/users").flash(.error, "Something went wrong")

Example of HTML

This package comes with a Leaf tag that makes it easy and convenient to display Flash messages. We suggest to use the Bootstrap package for rendering Bootstrap elements, but this package does not depend on it.

It's possible to loop through the different kinds of messages using:

  • all: All Flash messages no matter the kind.
  • successes: All Flash messages of type success.
  • information: All Flash messages of type info.
  • warnings: All Flash messages of type warning.
  • errors: All Flash messages of type error.

Further, using the message property you will be able to pull out the message of the Flash message. You can also get the kind by using the kind property. This property will hold one of the following values: success, info, warning or error. Lastly, you can use the bootstrapClass to get the relevant Bootstrap class:

  • success will return success.
  • info will return info.
  • warning will return warning.
  • error will return danger.

Not using the Bootstrap package

Without using any dependencies, this is how Flash messages could be rendered:

<div class="alerts">
#for(flash in flashes().all):
        Message: #(flash.message)
        Type: #(flash.kind)
    #endfor
</div>

Using the Bootstrap package

The below example uses the Vapor 3 Bootstrap package for generating the alert html.

<div class="alerts">
    #for(flash in flashes().all):
        #bs:alert(flash.bootstrapClass) {
            #(flash.message)
        }
    #endfor
</div>

Add the Flash html to one file and embed it in rest of your views or through a base layout, e.g.: #embed("alerts").

🏆 Credits

This package is developed and maintained by the Vapor team at Nodes.

📄 License

This package is open-sourced software licensed under the MIT license

flash's People

Contributors

brettrtoomey avatar casperhr avatar cweinberger avatar emarashliev avatar martinlasek avatar rasmusebbesen avatar siemensikkema avatar steffendsommer avatar tonyarnold avatar valen90 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

flash's Issues

Vapor 2

Now that Vapor 2 is released I'd love to see an official 1.0 tag supporting Vapor 2.

This package is awesome! I use it in all my projects. Kudos.

Vapor 3

Now that Vapor 3 is nearing a final release, what does the status look like for updating this library? I am more than happy to write the Vapor 3 version if someone can help point me in the right direction with request.storage not being around anymore.

Folder structure

Sort out folder structure (align with other packages) and split code into files when needed.

Can't seem to get it working.

Hey so I followed all of the instructions. I'm trying to add this globally. No matter what I do I can't seem to get the flash messages to render in my HTML. I copied and pasted the code from the README. Is there a way I can debug what is going on? I don't get any errors or anything. Thanks.

It doesn't work

The Flash package doesn't seem to work.

Following the documentation, double checking the configuration and requirements. I even created a new project just to configure flash and have one route that does nothing but redirect to the next one whilst adding a flash message.

configure.swift

import Leaf
import Vapor
import Flash

/// Called before your application initializes.
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
  /// Register providers first
  try services.register(LeafProvider())
  try services.register(FlashProvider())

  /// Register routes to the router
  let router = EngineRouter.default()
  try routes(router)
  services.register(router, as: Router.self)
    
  /// Use Leaf for rendering views
  config.prefer(LeafRenderer.self, for: ViewRenderer.self)

  /// Register middleware
  var middlewares = MiddlewareConfig() // Create _empty_ middleware config
  middlewares.use(FileMiddleware.self) // Serves files from `Public/` directory
  middlewares.use(ErrorMiddleware.self) // Catches errors and converts to HTTP response
  middlewares.use(SessionsMiddleware.self)
  middlewares.use(FlashMiddleware.self)
  services.register(middlewares)
}

routes.swift

import Vapor
import Flash

public func routes(_ router: Router) throws {
  router.get { req in
    return try req.view().render("welcome")
  }

  router.get("hello") { req -> Future<Response> in
    return req.future(req.redirect(to: "/").flash(.error, "Hey Listen!"))
  }
}

welcome.leaf

#set("title") { It works }

#set("body") {
  <div class="welcome">
    <div class="alerts">
      #flash() {
        #for(flash in all) {
          Message: #(flash.message)
          Type: #(flash.kind)
        }
      }
    </div>
    <img src="/images/it-works.png">
  </div>
}

#embed("base")

Putting a breakpoint in the package at the check whether flashes isEmpty shows, it is empty.. 🤔

Show flash messages only once

My impression of flash messages would be to show them only once. In this implementation, I see them only get added but not removed. Am I doing something wrong or am I missing something?

Otherwise, my suggestion would be to remove them when being rendered, so to insert the following line into FlashTag.swift at the end of the function render:

flash.flashes.removeAll()

Vapor Error causing not to Compile

Vapor requires a release 4.0.1 to solve dependencies properly. I forked, published the release, and it works fine.

Please just release 4.0.1 so that it will compile properly.

Thanks

About uses both flash tag and custom tag

The following codes won't work, the error message is No tag named `x` is registered.

services.register { container -> LeafTagConfig in
        var leafTagConfig = LeafTagConfig.default()
        leafTagConfig.use(XLeafTagRenderer(), as: "x")
        leafTagConfig.use(FlashTag(), as: "flash")
        return leafTagConfig
}

try services.register(FlashProvider())

The following codes won't work, the error message is No tag named `flash` is registered.

services.register { container -> LeafTagConfig in
        var leafTagConfig = LeafTagConfig.default()
        leafTagConfig.use(XLeafTagRenderer(), as: "x")
        return leafTagConfig
}

try services.register(FlashProvider())

The following codes will work.

try services.register(FlashProvider())

services.register { container -> LeafTagConfig in
        var leafTagConfig = LeafTagConfig.default()
        leafTagConfig.use(XLeafTagRenderer(), as: "x")
        leafTagConfig.use(FlashTag(), as: "flash")
        return leafTagConfig
}

So, I think there is no point in importing MutableLeafTagConfig

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.