LoginSignup
0
0

More than 3 years have passed since last update.

RailsでHTMLファイルを出力する

Posted at

やりたいこと

テンプレートに沿ったHTMLファイルを出力したい!

前提条件

以下のコマンドでBooksControllerを作成し、その中にHTMLファイルを出力するアクションを作成する。

  rails g controller books

テンプレートファイルを作成する

今回は以下のディレクトリを作成し、その中にテンプレートファイルを保存する。
app/views/books/template

html_template.html.erb
<!DOCTYPE html>
  <head>
    <meta charset="UTF-8">
    <title>本の詳細</title>
  </head>
  <body>
    <table>
      <tr>
        <th>タイトル</th>
        <td><%= @title %></td>
      </tr>
    </table>
  </body>
</html>

アクションを作成する

以下のようなアクションを作成する。

books_controller.rb
  def htmlfile_download
    @title = "本の題名"

    # 指定したファイルの中身を文字列で返す
    # layoutオプションの値をfalseにしておくと、レイアウトが適用されていない状態で取得できる
    template = render_to_string('books/template/html_template', layout: false)

    # HTMLファイルを生成
    send_data(template, filename: "ファイル名.html")
  end

以上です。

おまけ

render_to_stringで取ってきた値は以下のようになっています。

<!DOCTYPE html>
  <head>
    <meta charset="UTF-8">
    <title>本の詳細</title>
  </head>
  <body>
    <table>
      <tr>
        <th>タイトル</th>
        <td>本の題名</td>
      </tr>
    </table>
</html>
0
0
0

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
0
0