?之前Flask博客的文本編輯器比較簡陋,這里為博客添加個優雅易用的Tinymce文本編輯器。
github見:https://github.com/ikheu/my_flasky
1 項目中添加Tinymce
下載好Tinymce包以及語言包,并添加到項目中。添加到項目的方法,參考了這篇文章:Pyhton日記——給Flask加上優雅的TinyMCE編輯器。tinymce_setup.js是配置文件,設置了文本編輯器的語言、按鈕等。
2 編輯器表單
為了和其它表單的風格保持一致,這里仍使用了Flask-wtf表單。配置文件tinymce_setup.js中標識了id為content的標簽作為Tinymce編輯器顯示,這里為editor字段添加了相應的指示。測試發現,表單的editor顯示為Tinymce后,使用驗證函數無法對輸入進行判斷,這里將輸入的判斷放入視圖函數中。
class EditorForm(FlaskForm):title = StringField('標題', validators=[DataRequired(), Length(1, 64)])editor = TextAreaField('正文', id = 'content')submit = SubmitField('發表')
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):print(request.form)post = Post(title=request.form['title'],body_html=request.form['editor'],author=current_user._get_current_object())db.session.add(post)db.session.commit()return redirect(url_for('.post', id=post.id))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 代碼高亮
?在編輯界面上,代碼是可以高亮的:
?
提交后,由于沒有關聯到任何渲染樣式,代碼自然無法高亮:
為了保證提交前后的顯示是一樣的,仍想使用與tinyMCE編輯窗口中的樣式來渲染提交后的頁面。查了tinyMCE官網發現,需要手動配置js和css文件。下載渲染程序并添加到文章頁的html文件中:
{% block head %}{{ super() }} <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='prism.css') }}"> <script src="{{ url_for('static', filename='js/prism.js') }}"></script> {% endblock %}
刷新文章頁,顯示如下:
大功告成。
?