【问题标题】:How to run a function from EJS template?如何从 EJS 模板运行函数?
【发布时间】:2021-05-29 19:22:48
【问题描述】:

我正在尝试使用 ejs 模板中的 checkVowel() 函数。但它不起作用。

我从 home.ejs 得到一个字符串输入:

<body>
<div class="header">
    <h1>Just enter a string and I will tell you how many vowels are there...</h1>
    <form action="/" method="POST">
        <label for="strInput">Enter text</label>
        <input type="text" id="strInput" name="str">
        <input type="submit" value="Submit">
    </form>
</div>
</body>

这是我在 functions.ejs 中添加的 JavaScript 部分:

<% function checkVowel(str) {
    vowels = ['a', 'e', 'i', 'o', 'u']
    vowel_count = 0
    for (let i = 0; i < str.length; i++) { if (vowels.includes(str[i])) { vowel_count += 1; } } console.log(`There are ${vowel_count} vowels in the provided string.`)
} %> 

我正在使用 req.body 从 Express 解析我的数据。

const express = require('express')
const ejs = require('ejs')
const app = express()
const port = 3000

// View engine setup 
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true })); 
// app.use(bodyParser.json());


app.get('/', (req, res) => {
    res.render('home')
})

app.post('/', (req, res) => {
    const {str} = req.body;
    res.render('result', {str})
    // res.send(`Okay, checking: ${str}`)
})

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})

我真的很困惑如何运行我的函数。我不知道是将它包含在 .ejs 文件中还是创建一个单独的文件夹并使用 express.static()。

当有人在我的 home.ejs 文件中填写表格时,我想做什么。该字符串在我的 checkVowel() 函数中用作参数,然后在我的 ejs 模板中呈现 vowel_count。

【问题讨论】:

  • const vowel_count = (str.match(/[aeiou]/gi) || []).length;

标签: javascript ejs


【解决方案1】:

因此,经过大量的反复试验,我弄清楚了哪里出了问题。我需要在必要时添加 EJS 标签。出于某种原因,console.log 不适用于 EJS 模板。以下代码工作正常:

<% function checkVowel(str) { %>
    <% let vowels = ['a', 'e', 'i', 'o', 'u']  %>
    <% let vowel_count = 0 %>
    <% str = str.toLowerCase() %>
    <% for (let i = 0; i < str.length; i++) { %>
        <% if (vowels.includes(str[i])) { %> 
            <% vowel_count +=1; %>
        <% } %> 
    <% } %>
    <p> There are <%= vowel_count %> vowels in the provided string.</p> <% } %>

<%= checkVowel(str) %>

我正在使用表单传递 str 参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多