Express EJS:“值未定义”,但在“ If”中

时间:2019-05-16 15:03:32

标签: node.js express ejs

在Node中,我将tasks数组发送到某些路由,而不是其他路由。在这里,我正在发送tasks数据:

pagedata = {
    title: 'Task List App',
    tasks: [{name: 'a task'}]   <---
}
 res.render('index', pagedata);

EJS文件中的标记具有用于该任务数据的if

<% if (tasks) { %>
    ...
<% } %>

那很好。但是有些页面没有任务,所以这就是为什么我使用if的原因。但是,当我没有在task对象上包含pageData属性时,就像这样:

pagedata = {
    title: 'Task List App'
}
 res.render('index', pagedata);

我收到错误tasks is not defined。我认为您使用if的全部原因是因为该数据可能不存在。我想念什么?

2 个答案:

答案 0 :(得分:3)

所有变量均由ejs自动通过“ locals”对象传递,在您看来只需执行以下操作:

<% if(locals.tasks) { %>

如果未定义某些变量,它可以防止EJS崩溃。

此外,此locals对象也存在于res.locals中(如果您使用express的话),这意味着您还可以直接在中间件中为视图定义一些变量/函数:

app.use(function(req, res, next){
     res.locals.formatString = function(str){
         return str.toUpperCase();
     };

     res.locals.globalLang = "en";
     return next();
});

router.get("/index", function(req, res){
    res.render("index.ejs",{title: "index"});
});

// in index.ejs
<%- locals.formatString(locals.title); %>
<%- locals.globalLang; %>
....

答案 1 :(得分:1)

您可以这样问:

import * as React from 'react';

// Since Try Flow doesn't have access to these types
type ApolloClient<T> = any;
type moment = any;

type Props = {
  client: ApolloClient<any>,
  location: { 
    search: string,
  },
};

type SelectedDates = {
  startOn: moment,
  endOn: moment,
};

function withInitialSelectedDates(
  Component: React.AbstractComponent<Props>
): React.AbstractComponent<$Diff<Props, { initialSelectedDates: SelectedDates | void }>> {
  return class WrappedComponent extends React.Component<
    $Diff<Props, { initialSelectedDates: SelectedDates | void }>,
    { initialSelectedDates: SelectedDates | null }
  > {
    state = {
      initialSelectedDates: null,
    }

    getInitialSelectedDatesFromQueryString(): SelectedDates | null {
      if (true) {
        return { startOn: 'start', endOn: 'end' };
      } else {
        return null;
      }
      // use actual implementation; I just needed to satisfy type check
    }

    setInitialSelectedDatesOnGraphQLClient(selectedDates: SelectedDates | null): void {
      // implementation
    }

    componentDidMount(): void {
      const initialSelectedDates = this.getInitialSelectedDatesFromQueryString();
      this.setState({ initialSelectedDates });
      this.setInitialSelectedDatesOnGraphQLClient(initialSelectedDates);
    }

    render() {
      return (
        <Component
          {...this.props}
          initialSelectedDates={this.state.initialSelectedDates}
        />
      );
    }
  }
}