我正在尝试将Vue js集成到现有的rails应用程序中,并使用大量的瘦模板。如果我能在超薄的模板中使用vue指令(是的,这是可能的),获得一个HTML并将它传递给Vue实例进行进一步的开发,那就太好了。我知道有一些slim-lang加载器可以将slim编译成html,或者可以在<template lang="slim">中使用slim语法。
但我不想通过AJAX分别发送每个ruby/rails方法的结果。我希望Rails完成它的工作,并将结果HTML交给Vue实例。对此有什么想法和建议吗?
发布于 2019-01-17 07:52:33
我找到的解决办法很简单。您所需要做的就是将苗条标记封装在.slim视图中的vue组件标记中,并向其添加内联模板属性。
示例:
# header.html.slim
<v-header inline-template>
header
nav
- categories.each do |category|
= link_to category.name, category, '@click.prevent': 'doSomething'
</v-header>或
v-header inline-template=""
header
nav
- categories.each do |category|
= link_to category.name, category, '@click': 'doSomething'Ruby代码将首先执行,模板引擎将使用vue指令将所有内容转换为html,然后Vue将识别其指令并控制标记。在我实现这个之后,我摆脱了jquery和资产管道。但观点是一样的。我没有将任何html文件迁移到vue组件。通过这个特性,您可以将Vue js部分应用于现有的rails项目,并开始编写现代的javascript代码。
发布于 2018-10-12 13:16:37
没有银弹可以结合服务器端和客户端模板。即使您可以在服务器上呈现vue模板,也缺少关键上下文(客户机中页面的交互状态)。
有一些相当简单但有缺陷的技术可以用来组合服务器端和客户端呈现:
创建一个为视图服务的控制器
Rails.application.routes.draw do
scope 'templates' do
get '*path', to: 'templates#show'
end
endclass TemplatesController < ApplicationController
def show
if lookup_context.exists?(params[:path])
render template: params[:path]
else
head :not_found
end
end
endrequire 'rails_helper'
RSpec.describe "Templates", type: :request do
describe "GET /template/*path" do
it "fetches template if it exists" do
get '/templates/foo/bar.html.erb'
expect(response).to have_http_status(200)
expect(response.body).to match "TEST"
end
it "returns 404 if it does not exist" do
get '/templates/foo/non_existant.html.erb'
expect(response).to have_http_status(:not_found)
end
end
end然而,问题在于细节--只有在视图完全静态且不需要任何输入数据的情况下,这才能真正发挥作用。
没有布局的呈现视图
如果希望从控制器正常呈现,但不包括整个布局,则可以注册自定义格式:
# config/initializers/mime_types.rb
Mime::Type.register "text/x-html-template", :template有时,您可能需要停止spring,以便获取配置更改。
然后,可以禁用此格式的布局:
class ApplicationController < ActionController::Base
before_action :add_html_to_template_lookup!, if: -> { request.format.template? }
layout :is_template_request?
private
def is_template_request?
request.format.template? ? false : "application"
end
# this will make rails fall back to rendering the "normal" html views
def add_html_to_template_lookup!
request.formats << Mime::Type.lookup("text/html")
end
endhttps://stackoverflow.com/questions/52773259
复制相似问题