Rails中的参数化嵌套erb组件(Parametrized nested erb components in Rails)

编程入门 行业动态 更新时间:2024-10-26 09:18:57
Rails中的参数化嵌套erb组件(Parametrized nested erb components in Rails)

我对Rails很新,但有React的经验。 我想用erb文件来管理......我可以在React中这样做:

class MyElement extends Component { render() { return <div> some text {this.props.myFirstParam + this.props.mySecondParam} some another text </div> } } class MyBody extends Component { render() { return <body> <MyElement myFirstParam={1} mySecondParam={2} /> <MyElement myFirstParam={3} mySecondParam={5} /> <MyElement myFirstParam={7} mySecondParam={3} /> </body> } }

当然,我知道Rails在服务器端处理文件,但我只想显示组件嵌套的想法。 我想避免方法中的命令式字符串连接。 有没有一些好方法可以做到这一点?

I'm quite new with Rails, but have React experience. I'd like to manage with erb files sth I could do in React that way:

class MyElement extends Component { render() { return <div> some text {this.props.myFirstParam + this.props.mySecondParam} some another text </div> } } class MyBody extends Component { render() { return <body> <MyElement myFirstParam={1} mySecondParam={2} /> <MyElement myFirstParam={3} mySecondParam={5} /> <MyElement myFirstParam={7} mySecondParam={3} /> </body> } }

Of course I know that Rails process files on the server side, but I'd like just to show the idea of component nesting. I'd like to avoid imperative string concatenation in methods too. Is there some good way to do this?

最满意答案

好吧,我找到了方法。 我们可以使用render功能做到这一点。 我创建了名为_my_element.erb文件,如下所示:

<div> some text <%= myFirstParam + mySecondParam %> some another text </div>

它位于views文件夹中,这似乎很重要。

接下来在我插入的my_body文件中:

<%= render partial: "my_element.erb", locals: {myFirstParam: 1, mySecondParam: 2} %>

出于某种原因,文件的名称应以_ char开头,而partial参数中的路径不应包含它。

但毕竟,这是有效的。

Okay, I found the way. We can do this with render function. I created file named _my_element.erb which looks like this:

<div> some text <%= myFirstParam + mySecondParam %> some another text </div>

It's located in views folder, which seems to be important.

Next in my_body file I inserted:

<%= render partial: "my_element.erb", locals: {myFirstParam: 1, mySecondParam: 2} %>

For some reason name of file should begins with _ char, while path in partial parameter should't include it.

But after all, that works.

更多推荐

本文发布于:2023-07-31 09:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1341930.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   组件   参数   Rails   erb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!