9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Skinny Frameworkでスマホ対応したい

Last updated at Posted at 2014-03-08

スマホ対応というか、UserAgentごとにviewを切り替えたい。
ロジックはほぼ同じで、見た目が違う(CSS、HTML、JSが違う)という昔ながらのスマホ対応。

skinny-blank-appのアプリでは
src/main/scala/controller/ApplicationController.scala
がそのアプリの共通の親っぽいので、
ここのbeforeフィルタでUA判定することにする。
beforeActionでUA判定する。
あとはrenderをoverrideしてデバイスごとのviewを設定する。
これでcontrollerは共通でview、layoutを出し分けできる。

trait ApplicationController extends SkinnyController
  // with TxPerRequestFilter
  // with SkinnySessionFilter
  with ErrorPageFilter {

  val defaultDevice = "default"
  val smartDevice = "smartphone"

  private val extension = "ssp"
  private val mobileRegex = """.*(?i)(iphone|android|ipod).*""".r
  protected var device = defaultDevice

  def userAgent = request.getHeader("User-Agent")

  beforeAction() {
    device = userAgent match {
      case mobileRegex(m) => smartDevice
      case _ => defaultDevice
    }
  }

  override def render(path: String)(implicit format: Format = Format.HTML): String = {
    layout(device + "." + extension)
    super.render(path + "_" + device)(format)
  }
  // override def defaultLocale = Some(new java.util.Locale("ja"))

}

layoutはデバイス名.ssp、viewはindex_デバイス名.html.sspみたいな感じで作成。

src/main/webapp/WEB-INF/
                       layouts/
                              default.ssp
                              smartphone.ssp
                       views/
                             root/
                                  index_default.html.ssp
                                  index_smartphone.html.ssp

これでいいのか全くわからないが、とりあえずUAごとの異なる表示ができたっぽい。

https://github.com/ise/skinny-blank-app-multi/commit/471c41ee10f323b56a7d7084c4359178953e36a8
https://github.com/ise/skinny-blank-app-multi/commit/d232b7bc370e19b09ecffff24d7264e827669565

9
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?