想要渲染或仅显示文本中的几行

时间:2019-04-18 12:09:32

标签: python flask text jinja2 flask-sqlalchemy

我正在使用summernote编辑器来编写博客,并使用sqlalchemy来存储博客数据。所有功能正常。现在在主页上,我想显示每个博客无法显示的几行。

我在views.py上尝试了几个选项,但是它抛出了分页错误。 我还尝试了几种使用split和slice的选项,但由于编辑器html和实际文本而没有成功。

View.py用于获取博客文章数据。

make

index.html用于呈现博客文章数据。 这在for循环中

blog_posts = BlogPost.query.order_by(BlogPost.date.desc()).paginate(page=page,per_page=5)

在阅读此问题时,存储在sqlite表中Text(数据类型)列中的数据(html +实际文本)只会显示实际文本

<p>{{ post.text|safe }}</p>

预期结果-我只想显示3-5行文本。

1 个答案:

答案 0 :(得分:0)

您需要的是显示/隐藏更多内容按钮,如下面的代码所示。

在这里,我将字符数限制设置为30个或更多。如果字符超过30,则会显示“阅读更多”按钮。您也可以隐藏内容。

您可以调整字符数限制以适合您的选择。可以使用 Jquery / Ajax 和代码中所示的一些小CSS来实现。

尝试下面的代码,并确保您已连接到Internet,以便加载将使其工作的jquery文件。

根据您的情况,您需要将类文本传递给html段落元素 按照下面的

<p class="text">{{ post.text|safe }}</p>

这是代码示例

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">



<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

    function breakWords(paragraph, showtext){


        var words = paragraph.split(' ');

        var newText = '';

        for(i=0; i<words.length; i++){


            if(i<= showtext){

                newText += words[i] + ' ';

            }else {

                if (i == (showtext + 1)) newText += '... <span class="fulltext hide">';     

                newText += words[i] + ' ';

                if (words[i+1] == null) newText += '</span><a href="#" class="links"> &raquo; read more</a>';

            }

        }

        return newText;

    }


    $('.text').each(function () {

            $(this).html(breakWords($(this).html(), 10));

            $(this).children('span').hide();


        }).click(function () {


            var fulltext = $(this).children('span.fulltext');
            var links = $(this).children('a.links');


            if (fulltext.hasClass('hide')) {

                fulltext.show(10);
                links.html(' &raquo; hide');        
                fulltext.removeClass('hide');

            } else {

                fulltext.fadeOut(10);
                links.html(' &laquo; read more');           
                fulltext.addClass('hide');

            }

            return false;

        });

});

</script>

<style>


.links{color:#F60; font-weight:bold;text-decoration:none;}
</style>

</head>

<body>

<div id="textbox"> 
<p class="text">

The man behind my mystery. It was during the birthday celebration of David frank my first love that I 
met a young businessman who wons my heart over with enticing material gift. catapults me unto of the world promise me.
 a bliss.  
The man behind my mystery. It was during the birthday celebration of David frank my first love that I 
met a young businessman who wons my heart over with enticing material gift. catapults me unto of the world promise me.
 a bliss.</p>
</div>


</body>
</html>

来源link