Beego Development Light Blog--The fifth lecture article input

Source: Internet
Author: User
Tags key string

"Chick Software" beego Development Light Blog

Objective of this chapter: Add article Entry function
GitHub: When open, click the Star button in the upper right corner
Code Cloud: When opened, click on the Star button in the upper right corner

Front Page

1. We use "Wangeditor" as the Rich text editor

Wangeditor is a lightweight web Rich Text editor. Easy to configure and easy to use. Support Ie10+ Browser.

2 Add views->note_new.html file, the core code is as follows

<body class= "Lay-blog" > ... <form class= "Layui-form layui-form-pane" action= "" > <div class = "Layui-form-item" > <label class= "Layui-form-label" > title </label> <div class= "layui-i                        Nput-block "> <input type=" text "name=" title "required=" "value=" "            Lay-verify= "Required" placeholder= "Please enter title" autocomplete= "Off" class= "Layui-input" > </div> </div> <div class= "Layui-form-item layui-form-text" > <label C lass= "Layui-form-label" > Content </label> <div class= "Layui-input-block" > <div id= "Ed It "></div> </div> </div> <div class=" Layui-form-item "> < Button class= "layui-btn" lay-submit= "" lay-filter= "save" > Submit </button> </d Iv> </form>      ... 

The page works as follows: Image.png

3. Wangeditor Use

We only need to introduce the WangEditor.min.js file, call Window.wangeditor ("Element ID"). Create () to initialize the Rich Text page. I continue to modify the views->note_new.html file.

<body>...<form>... <div id="edit"><div> ...</form>...{{template "comm/footer.html" .}}<script type="text/javascript" src="/static/lib/wangEditor/wangEditor.min.js"></script><script>    layui.use([...], function () {        ...        // 初始化 wangEditor        var E = window.wangEditor;        var editor = new E('#edit');      // 图片不采用上传模式,直接保存到数据库        editor.customConfig.uploadImgShowBase64 = true;        editor.customConfig.pasteFilterStyle = false;        editor.customConfig.zIndex = 1;        editor.create();    });</script>

Defining Database Tables

New Models->note.go Definition Article table, the code is as follows

type Note struct {    gorm.Model    Key     string `gorm:"unique_index;not null;"` //文章唯一标示    UserID  int // 用户id    User    User  //用户    Title   string //文章标题    Summary string `gorm:"type:text"` //概要    Content string `gorm:"type:text"` //文章内容    Visit   int    `gorm:"default:0"` //浏览次数    Praise  int    `gorm:"default:0"` // 点赞次数}

Page display of new articles

1. We need to add a routing path for the new page of the article, so we have added another Notecontroller controller. Add the following code to the new Controllers->note.go file

type NoteController struct {    BaseController}// @router /new [get]func (ctx *NoteController) NewPage() {    ctx.Data["key"] = uuid.NewUUID().String()    ctx.TplName = "note_new.html"}

There is a CTX in the code above. data["key"] = uuid. Newuuid (). String (). Imagine if the user opens the new article page, maintain good data, when the click on the Save button, not careful more than a few times, is the system will add a few more duplicate article records? Therefore, we have added CTX. data["key"] = uuid. Newuuid (). String () causes each new article page to be opened with a unique key on the current page. When you click Save, the page key will be passed back to the background, so that the background can be more key open to determine whether the user is new or modified! Just said the situation users click multiple times, the first is added, after all is modified.

2. The function related to the article adjustment must be the logged-in user, and the logged-on user must be an administrator. We modify the Notecontroller controller and add the Nestprepare method. Each request that is sent, when routed to the appropriate method of the Notecontroller controller, calls the Nestprepare method to add that the user must log in and be an administrator. Modify the Controllers->note.go code as follows

func (ctx *NoteController) NestPrepare() {    ctx.MustLogin()//用户必须登陆,没有登陆就返回错误    if ctx.User.Role != 0 {//不是管理员,之前返回错误        ctx.Abort500(syserrors.NewError("您没有权限修改文章", nil))    }}

3. We use the Beego annotation route, I need to inject the Notecontroller controller into the Beego's include. Modify the Routers->router.go file and modify the following:

func init() {    ...    beego.AddNamespace(        beego.NewNamespace(            "note",            beego.NSInclude(&controllers.NoteController{}),        ),    )}

Here, the routing path for the new article is: note/new

4. Add a new article to the action portal, modify the User Management page (views->user.html) Add button, click to jump to the article new page. Modify the views->user.html file and modify the code as follows:

...{{if .IsLogin}}    ...  {{if eq .User.Role 0}}    

New page saving feature for articles

1. The new routing path that we have added to the article is:/note/save/:key

2. Add page logic, when saving, we will page user maintained article data with Ajax send POST request to the background service, the service for the path is/note/save/:key, we need to modify the views->note_new.html file, add the following code

...<script>    layui.use(['form', 'jquery', 'layer', 'sysn'], function () {        ...      form.on('submit(save)', function (fromdata) {        sysn.post("/note/save/{{.key}}", fdata)            .success(function (data) {               layer.msg("保存成功!");               if (data.action) {                    setTimeout(function () {                         window.location.href = data.action;                    }, 300)               }            }).run();      }}</script>...

3. Tuning the Database

3.1 We previously defined the article database in the table structure of key is not repeatable, is the only sign of the article. Therefore, we need to determine whether the key exists, if there is an update does not exist on the new. We modified models->note.go to add a method to query the article by key.

func QueryNoteByKeyAndUserId(key string, userid int) (note Note, err error) {    return note, db.Model(&Note{}).Where("key = ? and user_id = ?", key, userid).Take(&note).Error}

3.2 Need to save the article data to the database, so we want to add a method to save the article data. The code is as follows:

func SaveNote(n *Note) error {    return db.Save(n).Error}

4. Adjusting the controller Notecontroller

4.1 In the future we need to list the article on the first page, we can not display all the content of the article on the homepage, so we need to intercept the first 600 words of the article as a summary of the article to save to the database. Here we use the Golang third-party library github.com/puerkitobio/goquery, which is used to parse the HTML document of the article. Modify Controllers->note.go Add a method to intercept the article summary, the code is as follows.

// 截取content摘要//content >文章 > html文档func getSummary(content string) (string, error) {   // bytes.Buffer,非常常用。    var buf bytes.Buffer    buf.Write([]byte(content))    // 用goquery来解析content    doc, err := goquery.NewDocumentFromReader(&buf)    if err != nil {        return "", err    }    // Text() 得到body元素下的文本内容(去掉html元素)    str := doc.Find("body").Text()    // 截取字符串    if len(str) > 600 {        str = str[0:600] + "..."    }    return str, nil}

4.1 Add the method to save the article, modify the Controllers->note.go, the code is as follows

@router/save/:key [Post]func (CTX *notecontroller) Save () {//Get the page passed over key key: = CTX.    Ctx.Input.Param (": Key")//empty, empty to return an error. Title: = ctx. Getmuststring ("title", "title cannot be empty!") ") Content: = CTX. Getmuststring ("Content", "contents cannot be empty!") ")//Get the article Summary summary, _: = getsummary (content)//query article note according to key, err: = CTX. Dao.querynotebykeyanduserid (key, int (CTX. user.id)) var n models. Note If Err! = Nil {//There is an error, but when the error is not an error that does not find the data, it returns an error if err! = Gorm. Errrecordnotfound {ctx. Abort500 (syserrors. NewError ("Save failed! ", err)}//Do not find the data, then do the new article operation n = models.            note{Key:key, Summary:summary, Title:title, Files:files, Content:content, Userid:int (CTX. user.id),}} else {//query does not error, this exists article, then do update article operation n = Note N.title = Title n.content = Co Ntent n.summary = Summary N.files = Files N.updatedat = time. Now ()}//WarrantySave Article Savenote is based on the ID to determine whether the update or new, ID exists on the update, does not exist on the new.    The above update operation is, the article records from the database, modify the data, so there is an ID. If err: = CTX. Dao.savenote (&n); Err! = Nil {ctx. Abort500 (syserrors. NewError ("Save failed! ", err)} ctx. Jsonok ("Success")}

Users save the article function, we have completed

Summarize

In this talk, we realized the function of the article input, we review the implementation process is divided into two major steps:

    1. The first step to getting the job done
      1.1 Draw a new page of the article.
      1.2 Design the database table structure of the article well.
      1.3 Add route let 1.1 new page, can access to.
    2. The second step to achieve the article preservation
      2.1 Modify the new page and send the request to the background when saving.
      2.2 Implement the logic of the background, save the data to the database.

Next, we will implement the article display, the article changes and the article deletion function. Say goodbye.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.