Home  >  Article  >  Web Front-end  >  Development of Nodejs views and models

Development of Nodejs views and models

php中世界最好的语言
php中世界最好的语言Original
2018-03-16 14:19:071825browse

This time I will bring you the development of Nodejs views and models. What are the precautions for the development of Nodejs views and models? The following is a practical case, let's take a look.

Navigation

The front-end layout uses bootstrap, which is downloaded from the official website and placed in the public folder. Open layout.jade and make a navigation first.

doctype html
html
  head
    meta(name='viewport', content='width=device-width, initial-scale=1.0')
    title= title
    link(rel='stylesheet', href='/bootstrap/css/bootstrap.css')
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    nav.navbar.navbar-default.navbar-fixed-top.navbar-inverse
     .container
      .navbar-header
        a.navbar-brand(href='/') ReadingClub
      .collapse.navbar-collapse
       ul.nav.navbar-nav.pull-right
         li
          a(href='/') 首页
         li
          a(href='/Books') 读物
         li
          a(href='/About') 关于
         li
          a(href='/Register') 注册
         li
          a(href='/Login') 登录
     #bodycontent.container        block content
   footer.container
       .row
          .col-xs-12
            small © stoneniqiu 2016
    script(src='/javascripts/jquery-1.11.1.min.js')
    script(src='/bootstrap/js/bootstrap.min.js')
block content is introduced above and can be understood as a placeholder. Because I am still not used to stylus, I just write css directly, so that VS will have smart prompts.

style.css

body {
 font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
    background: gainsboro;
}a {
  color: #00b7ff;
}.navbar-default {
  background-color: #444;
  border-color: black;
}.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
    color: #ffffff;
    background-color:#222;
}.navbar-default .navbar-nav > li > a{
    color:  #ccc;
}a.navbar-brand{color: #fff !important}
View Code

Run it and see the navigation bar

If you access registration and login, 404 will be reported because the corresponding page has not been set before.

Such a page appears because in the above, there are settings in app.js

app.use(function (req, res, next) {    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});
Looking back at layout.jade, there is no one

The html tag starts directly with the element name or style name. This writing method is similar to writing html in sublime. The attributes are written in brackets and the text content is separated by spaces. The nesting relationship of elements is controlled through strict indentation. The advantage of this is that the amount of code is smaller and the hierarchy is clearer. However, when the code is long, it is difficult to judge the exact position of the indentation. Misalignment can easily cause accidental nesting. My current experience is to write from left to right, rather than from top to bottom. In other words, when writing HTML with Jade, write the outermost elements first, and then gradually write the sub-elements inside. Instead of writing them one by one from top to bottom, this will cause problems with indentation.

Model and View

Back to home.js, we use JavaScript to create a books model, including title, info, rating, img and tags. Because the database has not been used yet, create it directly here.

books:

var books = [
{
    id: 0,
    title: "深入浅出Node.js",
    info: "朴灵 / 人民邮电出版社 / 2013-12-1 / CNY 69.00",
    rating: 5,
    img: "https://img3.doubanio.com/mpic/s27269296.jpg",
    tags: ["node", "深入浅出"],
    brief: '本书从不同的视角介绍了 Node 内在的特点和结构。由首章Node 介绍为索引,涉及Node 的各个方面,主要内容包含模块机制的揭示、异步I/O 实现原理的展现、异步编程的探讨、内存控制的介绍、二进制数据Buffer 的细节、Node 中的网络编程基础、Node 中的Web 开发、进程间的消息传递、Node 测试以及通过Node 构建产品需要的注意事项。最后的附录介绍了Node 的安装、调试、编码规范和NPM 仓库等事宜。本书适合想深入了解 Node 的人员阅读。'
    ,ISBN: 9787115335500
    },
{
    id: 1,
    title: "程序员修炼之道 : 从小工到专家",
    info: "Andrew Hunt、David Thomas / 马维达 / 电子工业出版社 / 2005-1 / 48.00元",
    rating: 5,
    img: "https://img3.doubanio.com/mpic/s3957863.jpg",
    tags: ["程序人生", "软件开发"],
    brief: '《程序员修炼之道》由一系列的独立的部分组成,涵盖的主题从个人责任、职业发展,直到用于使代码保持灵活、并且易于改编和复用的各种架构技术。利用许多富有娱乐性的奇闻轶事、有思想性的例子以及有趣的类比,全面阐释了软件开发的许多不同方面的最佳实践和重大陷阱。无论你是初学者,是有经验的程序员,还是软件项目经理,本书都适合你阅读。'
    ,ISBN: 9787505397194
    },
{
    id: 2,
    title: "Getting MEAN with Mongo, Express, Angular, and Node",
    info: "Simon Holmes / Manning Publications / 2015-11-26 / USD 44.99",
    rating: 4,
    img: "https://img3.doubanio.com/mpic/s27676844.jpg",
    tags: ["node", "web开发", "编程"],
    brief: 'MEAN栈开发,比较详尽的的应用开发书籍'
    , ISBN: 9781617292033
    }
];
 res.render('books', { title: 'Books', books: books });
jade
模型其实就是一个json对象,接下来我们修改books页面的布局。这里用左右布局,稍加调整
extends layout
block content 
  .row
   .col-md-9.page
     each book in books
       .row.booklist
         .col-md-2
          img(src='#{book.img}')
         .col-md-10
            p
             a(href="/Detail/#{book.id}")=book.title
            p=book.info
            p            - for (var i = 1; i <= book.rating; i++)
                span.glyphicon.glyphicon-star            - for (i = book.rating; i < 5; i++)
                span.glyphicon.glyphicon-star-empty
            p.tags
             each tag in book.tags
              span=tag
   .col-md-3
     .userinfo
       p stoneniqiu

View Code

 res.render(&#39;books&#39;, { title: &#39;Books&#39;, books: books });

Add books to home.js. The model is actually a json object. Next, we modify the layout of the books page. Here we use the left and right layout and adjust it a little,

extends layout
block content 
  .row
   .col-md-9.page
     each book in books
       .row.booklist
         .col-md-2
          img(src=&#39;#{book.img}&#39;)
         .col-md-10
            p
             a(href="/Detail/#{book.id}")=book.title
            p=book.info
            p
            - for (var i = 1; i <= book.rating; i++)
                span.glyphicon.glyphicon-star
            - for (i = book.rating; i < 5; i++)
                span.glyphicon.glyphicon-star-empty
            p.tags
             each tag in book.tags
              span=tag
   .col-md-3
     .userinfo
       p stoneniqiu

gets the effect:

Of course these are still static, let’s introduce the jade engine. jade is a high-performance

template engine for node.

1. Master page

Using bootstrap’s fence layout, it is divided into left and right parts. extends layout means introducing the layout master page, and the block content in the layout will be replaced by the content in the block content of the current page. You can also define multiple blocks

//- layout.jade
doctype html
html
  head    block title
      title Default title
  body    block content

Reference page:

//- index.jade
extends layout
block title
  title Article Title
block content
  h1 My Article

Generated html:

<!doctype html><html>
  <head>
    <title>Article Title</title>
  </head>
  <body>
    <h1>My Article</h1>
  </body></html>
2. Loop

each book in books

represents the loop output model, in In the view of Asp.net MVC, you need to define the type of Model first. Jade omits this model and directly obtains the attributes of the model. It also supports for loops, the preceding ‘-’ sign is essential.

- for (var i = 1; i <= book.rating; i++)
         span.glyphicon.glyphicon-star- for (i = book.rating; i < 5; i++)
         span.glyphicon.glyphicon-star-empty

3. Assignment

Space assignment, this space cannot be missing, otherwise jade will treat ptext as an element. All spaces following are considered strings.

  p  text  输出  <p>text<p>
So if it is an output variable, it must be assigned with ‘=’.

  a(href="/Detail/")=book.title
But if it is a combination of string input, you should use #{}

 img(src='#{book.img}')
  p  读过#{book.title}
If you don’t want to escape the content!{}, - var means

define variables, which is equivalent to @{}

- var riskyBusiness = "<em>Some of the girls are wearing my mother's clothing.</em>";
.quote
  p Joel: !{riskyBusiness}
Output in Razor

<p class="quote">
  <p>Joel: <em>Some of the girls are wearing my mother's clothing.</em></p></p>
4. Attributes

If you are adding an element attribute, complete it in the brackets after the element

a(href="/Detail/")=book.title
Output:

<a href="/Detail/">深入浅出Node.js</a>

如果是多个属性用逗号隔开,也可以换行

a(class='button', href='google.com') 
input(
  type='checkbox'
  name='agreement'
  checked
)

还可以加入表达式

- var authenticated = true
body(class=authenticated ? 'authed' : 'anon')

而Razor要在元素里面写表达式就有点丑陋。

@{    var ischeck = true;
}<input type="checkbox" @if (ischeck)
                       {                           @Html.Raw("class=&#39;selected&#39;")
                       }              
    />

 更多特性请看:http://jade-lang.com/reference/attributes/

5.子视图 

这里用子视图还不太准确,我们已经知道通过extends 和 block 来引入母版页,并按模块取代内容。而子视图主要是强调复用,是嵌入到别的视图文件中。jade是用mixin(混合)定义一个部分视图,用‘+’使用 例如:

mixin list
  ul
    li foo
    li bar
    li baz
 
       +list
       +list

输出

比如把页面上显示星星的部分提出来,在view文件夹下建一个_include文件夹,并创建一个rating.jade文件:

mixin outputRating(rating)  - for (var i = 1; i <= rating; i++)
    span.glyphicon.glyphicon-star  - for (i = rating; i < 5; i++)
    span.glyphicon.glyphicon-star-empty

这样在页面上引用

include _includes/rating

然后在指定位置输出,主要有‘+’号。

 p    +outputRating(book.rating)

这里的mixin就相当于是一个JavaScript函数,可以传递多个参数。 更多内容可以移步 http://jade-lang.com/ jade官网。

同理创建了detail.jade 和index.jade

detail.jade

extends layout
include _includes/rating
block content
  .row
   .col-md-9.page.bookdetail
     h3=book.title
     .row
      .col-md-2
           img(src='#{book.img}')
      .col-md-10
            p=book.info
            p
             +outputRating(book.rating)
            p.tags
             each tag in book.tags
              span=tag
            p ISBN:#{book.ISBN}
     h3 内容简介
     p.brief=book.brief    
   .col-md-3
     .userinfo
       p stoneniqiu

View Code

index.jade

extends layout
block content 
  .row
   .col-md-9.page
     .row.topictype
       a.label.label-info(href='/')  全部
       a(href='/') 读书
       a(href='/') 书评
       a(href='/') 求书
       a(href='/') 求索
     each topic in topics
       .row.topiclist
         img(src='#{topic.img}')
         span.count
            i.coment=topic.commentCount
            i /
            i=topic.visitedCount
         span.label.label-info=topic.type
         a(href='/')=topic.title
         span.pull-right=topic.postTime
         a.pull-right.author(href='/')=topic.author
   .col-md-3
     .userinfo
       p stoneniqiu

View Code

至此,我们创建了三个静态页面,基本熟悉了jade语法。当然jade不止这些,后期随着项目的深入再不断的探索。

部署:

目前我已经将代码提交到github上,然后部署在heroku上。

github:https://github.com/stoneniqiu/ReadingClub 有兴趣的朋友可以一起开发学习。

观摩请戳:https://stoneniqiu-mean.herokuapp.com/ 

heroku提供了三百兆的免费空间,还有个规则的域名,如何部署请移步:三步将Node应用部署到Heroku上

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Nodejs使用Mongoose创建模型及API 

FTP的文件管理

The above is the detailed content of Development of Nodejs views and models. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn