当前位置: 首页 > Web前端 > CSS

基于阿里egg框架搭建博客(七)——编辑文章

时间:2023-03-30 19:00:25 CSS

相关文章基于阿里egg框架搭建博客(一)——开发准备基于阿里egg框架搭建博客(二)————HelloWorld基于阿里egg框架搭建博客(三)——注册登录基于阿里egg框架搭建博客(四)——访问控制基于阿里egg框架搭建博客(五)——设置顶部导航栏基于阿里egg框架搭建博客(六)——浏览和发布文章基于阿里egg框架搭建博客(七)——编辑文章githttps://github.com/ZzzSimon/e……喜欢就点个赞!编辑带有文字的文章,首先要获取文章的原始内容,然后放到编辑页面,给用户呈现“半成品”的状态,再次保存文章即可。页面设计我的文章页面编辑页面功能设计我的文章页面标题显示是否保密,标题后有编辑按钮。点击编辑按钮进入编辑页面,重新编辑文章前端代码myarticle.tpl我的文章页面我们创建/app/view/article/myarticle.tplpage:{%extends"parent.tpl"%}{%blockhead%}我的文章{%endblock%}{%blockcontent%}

我的文章

{%foriteminlist%}
{{helper.formatInvisible(item.invisible)}}{{item.title}}编辑
{{item.author}}最后更新于{{helper.formatTime(item.update_time)}}
{%endfor%}{%endblock%}这里要注意一点:helper.formatInvisible和helper.formatTime的作用是格式化后端返回的参数。当然,你也可以在后端代码中执行这些逻辑,但我更希望后端代码尽可能简单。格式化应该归属于前端类。如果模板的渲染属于后端逻辑,那我没说==。关于helper的使用:https://eggjs.org/zh-cn/basic...helper.jsconstmoment=require('moment');//timeformatexports.formatTime=time=>moment(time).format('YYYY-MM-DDHH:mm:ss');exports.formatInvisible=invisible=>invisible===1?'confidential':'';modify.tpl编辑文章页面我们创建/app/view/article/modify.tplpage:{%extends"parent.tpl"%}{%blockhead%}Editarticle{%endblock%}{%块内容%}文章标题:
{{article.detail}}
保存
{%endblock%}{%blockscript%}{%endblock%}end生成ArticleController后,我们添加了如下内容:asyncmyarticle(){constctx=this.ctx;constarticleList=awaitctx.service.article.getArticleByAuthor(ctx.session.user.username);awaitctx.render('article/myarticle.tpl',{list:articleList});等待service.article.getArticleById(ctx.params.id);等待ctx.render('article/modify.tpl',{article:article})}asyncmodify(){const{ctx,service}=this;constarticle=ctx.request.body.article;constnowTime=newDate();article.update_time=nowTime;constresult=awaitservice.article.modify(article);if(result){ctx.body={flag:'1',msg:'保存成功',url:'/article/'+article.id+'.htm'}}else{ctx.body={flag:'0',msg:'保存失败'}}}文章我们添加以下服务:asyncmodify(article={}){constres=awaitthis.app.mysql.update('article',article);返回res.affectedRows===1;}asyncgetArticleByAuthor(author){constsql="SELECTid,url,title,author,update_time,invisibleFROMarticleWHEREauthor=";constlist=awaitthis.app.mysql.query(sql,[作者]);返回列表;}asyncgetArticleById(id){constsql="SELECTid,title,detail,invisibleFROMarticleWHEREid=";constlist=awaitthis.app.mysql.query(sql,[id]);返回列表[0];}end看完如果觉得有用,请给作者点个赞!谢谢你!