在show.html.erb
页上,我有一个项目列表:
<div id="shopOffersPartial">
<%= render "shops/shop_offers", offers: @offers %>
</div>
在部分中,仅存在一个循环。 @offers
来自后端
<% offers.each do |offer| %>
<%= render "shared/mini_offer_card/content", offer: offer, shop: @shop %>
<% end %>
我想在每次按键事件中过滤元素子。为此,我听了一个输入。我在Webpack中有JS逻辑。
const shopFilterProductsInput = document.getElementById("shopFilterProducts");
const shopId = shopFilterProductsInput.dataset.shopid;
const shopOffersPartial = document.getElementById("shopOffersPartial");
const filterOfferes = (e) => {
let inputValue = shopFilterProductsInput.value;
const url = `/shops/${shopId}?query=${inputValue}`;
fetch(url)
.then(function() {
shopOffersPartial.innerHTML = "<%= render 'shops/shop_offers', offers: @offers %>";
})
.catch(function() {
// This is where you run code if the server returns any errors
});
}
if (shopFilterProductsInput) {
shopFilterProductsInput.addEventListener("keyup", filterOffers)
}
我的问题在代码的这一部分:
fetch(url)
.then(function() {
shopOffersPartial.innerHTML = "<%= render 'shops/shop_offers', offers: @offers %>";
})
获得响应后,我要重新渲染包含项目列表的部分。
在rails中,使用.js.erb,您可以执行以下操作:
// app/views/reviews/create.js.erb
// Here you generate *JavaScript* that would be executed in the browser
function refreshForm(innerHTML) {
const newReviewForm = document.getElementById('new_review');
newReviewForm.innerHTML = innerHTML;
}
function addReview(reviewHTML) {
const reviews = document.getElementById('reviews');
reviews.insertAdjacentHTML('beforeend', reviewHTML);
}
<% if @review.errors.any? %>
refreshForm('<%= j render "reviews/form", restaurant: @restaurant, review: @review %>');
<% else %>
addReview('<%= j render "reviews/show", review: @review %>');
refreshForm('<%= j render "reviews/form", restaurant: @restaurant, review: Review.new %>');
<% end %>
但是我在一个Webpack文件中。我不能使用Rails助手。
如何使用Webpack渲染Rails助手?
答案 0 :(得分:0)
此代码
fetch(url)
.then(function() {
shopOffersPartial.innerHTML = "<%= render 'shops/shop_offers', offers: @offers %>";
})
应替换为:
fetch(url)
.then(function(res) {
return res.text();
}).then(function(html) {
shopOffersPartial.innerHTML = html;
});
您不必在JS文件中使用render
。 /shops/${shopId}?query=${inputValue}
访问的控制器应返回所需的html。像这样:
def show
# offers = ???
# ...
respond_to do |format|
format.html { render 'shops/show' }
format.js { return plain: render_to_string("shops/shop_offers", offers: offers, layout: false) }
end
end