如何在ejs模板中使用in_array

时间:2018-01-04 04:47:07

标签: node.js express ejs

如何在ejs模板中使用in_array或类似内容?

这是我在php上使用它的方式:

<?php
$cur_repository_id = array();
foreach($dbrepos as $row){
    $shared_ids = $row['shared_ids'];
    if(in_array($user_id, $shared_ids)){
        $selected = "selected";
        $cur_repository_id[] = $row['rep_id'];
    }else{
        $selected = "";
    }
?>
<option value="<?php echo $row['rep_id'];?>" <?php echo $selected;?>><?php echo $row['namespace'];?></option>
<?php
}
?>

1 个答案:

答案 0 :(得分:2)

javascript中in_array的等效值为includes

因此,如果您想将数组从Node.js传递到ejs文件,则可以执行以下操作:

res.render('index', {numbers : [1, 23, 44]});

然后在ejs内,您可以使用方法includes,例如:

<body>
    <% if(numbers.includes(44)){ %>
        <h1>44 exists</h1>
    <% } else{ %>
        <h1>44 not exists</h1>
    <% } %>
</body>

此外,您可以使用方法indexOf,它返回数组中给定值的索引。