之前Flask博客的文本编辑器比较简陋,这里为博客添加个优雅易用的Tinymce文本编辑器。
1、项目中添加Tinymce
下载好Tinymce包以及语言包,并添加到项目中。添加到项目的方法,参考了这篇文章:Pyhton日记——给Flask加上优雅的TinyMCE编辑器。tinymce_setup.js是配置文件,设置了文本编辑器的语言、按钮等。
2、编辑器表单
为了和其它表单的风格保持一致,这里仍使用了Flask-wtf表单。配置文件tinymce_setup.js中标识了id为content的标签作为Tinymce编辑器显示,这里为editor字段添加了相应的指示。测试发现,表单的editor显示为Tinymce后,使用验证函数无法对输入进行判断,这里将输入的判断放入视图函数中。
class EditorForm(FlaskForm): editor = TextAreaField('', id = 'content') submit = SubmitField('Submit')
3、视图函数
使用request.method判断请求为POST后,判断输入是否为空,若无输入则给予flask消息提醒。若已登录的用户具有写博客的权限,则输入的内容作为Post的body_html属性创建新的博客。Tinymce将输入的文本内容转为html代码,因此这里使用body_html,而不使用body。
@main.route('/editor', methods=['GET', 'POST']) @login_required def editor(): form = EditorForm() if request.method == 'POST': if not form.editor.data: flash('Write something.') return render_template('editor.html', form=form) if current_user.can(Permission.WRITE_ARTICLES): post = Post(body_html=request.form['editor'], author=current_user._get_current_object()) db.session.add(post) return redirect(url_for('.index')) return render_template('editor.html', form = form)
4、前端
在editor.html中加入tinymce.min.js、tinymce_setup.js这两个文件。使用wtf.quick_form渲染编辑器表单。
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Editor{% endblock %}
{% block head %}
{{ super() }}
<script src="{{ url_for('static', filename='tinymce/js/tinymce/tinymce.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/tinymce_setup.js') }}"></script>
{% endblock %}
{% block page_content %}
{{ wtf.quick_form(form) }}
{% endblock %}
5、显示效果
编辑器界面显示:
写些输入测试,比之前的好用多了。