def post_loop(max_posts): posts = Post.objects.filter( status__title="Published").order_by('-post_date')[:max_posts] output = "" for x in range(0, len(posts)): post = posts[x] permalink = functions.permalink(post.category.slug, post.slug) summary = Truncator(post.content_html) properties = { 'TITLE': post.title, 'TITLE_LINK': functions.make_link(permalink, post.title), 'PERMALINK': permalink, 'BODY': mark_safe(summary.words(100, html=True)), 'CATEGORY': post.category, 'POST_DATE': post.post_date, 'CREATED_DATE': post.created, 'LAST_EDIT_DATE': post.last_edited, 'AUTHOR': post.author, 'LAST_EDITOR': post.last_editor, } output += render_to_string( functions.get_template_file_path("postloop"), properties) return output
def find_post_content(feed_obj, entry): """Find the correct content field for a post.""" try: content = entry["content"][0]["value"] except (IndexError, KeyError): content = entry.get("description") or entry.get("summary") or "" if '<img' not in content: # if there's no image and the we add an image to the feed def build_img(img_dict): try: # The tag is url instead of src... pain img = "<img src='%s'" % img_dict.get("url") except KeyError: return '' img_dict.pop('url') for attr in img_dict.items(): img += "%s='%s'" % (attr[0], attr[1]) img += ">" return img try: thumbnail = entry["media_thumbnail"][0] img = build_img(thumbnail) except (IndexError, KeyError): img = "" content = img + content try: truncator = Truncator(text=content) content =truncator.words(num=conf.DEFAULT_ENTRY_WORD_LIMIT, html=True) except UnicodeDecodeError: content = "" return feed_content_optimizer.optimize(content)
def find_post_content(feed_obj, entry): """Find the correct content field for a post.""" try: content = entry["content"][0]["value"] except (IndexError, KeyError): content = entry.get("description") or entry.get("summary") or "" if '<img' not in content: # if there's no image and the we add an image to the feed def build_img(img_dict): try: # The tag is url instead of src... pain img = "<img src='%s'" % img_dict.get("url") except KeyError: return '' img_dict.pop('url') for attr in img_dict.items(): img += "%s='%s'" % (attr[0], attr[1]) img += ">" return img try: thumbnail = entry["media_thumbnail"][0] img = build_img(thumbnail) except (IndexError, KeyError): img = "" content = img + content try: truncator = Truncator(text=content) content = truncator.words(num=conf.DEFAULT_ENTRY_WORD_LIMIT, html=True) except UnicodeDecodeError: content = "" return feed_content_optimizer.optimize(content)
def render(self, value): """Overload render to optionally truncate words.""" value = super().render(value) if self.truncate_words is not None: trunc = Truncator(value) value = trunc.words(self.truncate_words) return value
def get_excerpt(self, max_words=55, end_text='...'): if not self.excerpt_html: truncator = Truncator(self.content_html) if end_text == '...': end_text = '…' return mark_safe(truncator.words(max_words, end_text, html=True)) else: return mark_safe(self.excerpt_html)
def _get_teaser(self): """ Retrieve some part of the article or the article's description. """ if not self._teaser: if len(self.description.strip()): self._teaser = self.description else: truncator = Truncator(self.rendered_content) self._teaser = truncator.words(WORD_LIMIT, html=True) return self._teaser
def notify_question_author(answer): title_truncated = Truncator(answer.question.title) subject = "Новый ответ к вопросу {} - Hasker".format( title_truncated.words(5)) message = """ <p>Получен новый ответ от пользователя {answer_author} к вашему вопросу <a href="{q_url}">{q_title}</a>:</p> <p>{a_text}</p> """.format(answer_author=answer.author.username, q_url=answer.question.url, q_title=title_truncated.words(10), a_text=Truncator(answer.text).words(25)) from_email = settings.TECH_EMAIL recipient_list = [answer.author.email] send_mail(subject, message, from_email, recipient_list, fail_silently=True)
def get_excerpt(self, max_words=20, end_text='...'): content = self.get_content() if hasattr(content, '__html__'): # The __html__ attribute means the content was previously # marked as safe, so can include HTML tags. truncator = Truncator(content.__html__()) if end_text == '...': end_text = '…' return mark_safe(truncator.words(max_words, end_text, html=True)) else: return Truncator(content).words(max_words, end_text, html=False)
def avoid_truncated_word(self, text): """Truncate in a way that text will be shorter than max_length and won't be cut in the middle of a word""" words = text.split() if not words: return text truncator = Truncator(text) last_word = text.split()[-1] text = truncator.chars(self.max_length, '') truncated_last_word = text.split()[-1] if truncated_last_word != last_word: # last word is cut. So, remove it num_words = len(text.split()) text = truncator.words(num_words - 1) return text
def item_description(self, item): description = '<p>Election Date: <strong> %s </strong></p>' % ( dateformat.format(item.date, 'N d, Y')) if item.registered_voters > 0: description += '<p>Registered Voters: <strong> %s </strong></p>' % ( str(format(item.registered_voters, ',d'))) if item.show_results and item.cast_votes > 0: description += '<p>Cast Votes: <strong> %s </strong></p>' % (str( format(item.cast_votes, ',d'))) text = Truncator(item.description) description += text.words(30) return description
def get_meta_data(self, request): truncator = Truncator(strip_tags(self.content)) description = truncator.words(35) image = '' full_domain = '{}://{}'.format(settings.META_SITE_PROTOCOL, settings.META_SITE_DOMAIN) if self.hero_image: thumbnail = get_thumbnail(self.hero_image, '900x350', crop='center') image = '{}{}'.format(full_domain, thumbnail.url) url = '{}{}'.format(full_domain, self.get_absolute_url()) return { 'type': 'article', 'title': self.title, 'description': description, 'image': image, 'url': url, }
def title(self): truncator = Truncator(self.topics) return truncator.words(12)
def __unicode__(self): if self.wrapper: text = Truncator(u'%s: %s' % (self.wrapper, strip_tags(self.body))) else: text = Truncator(strip_tags(self.body)) return Truncator(text.words(7)).chars(38)
def label_for_value(self, value): key = self.rel.get_related_field().name obj = self.rel.to._default_manager.get(**{key: value}) trunc = Truncator(obj) return trunc.words(obj, 14)
def item_description(self, item): truncator = Truncator(item.summary) return truncator.words(75, html=True)
def test_string_formatting(self): """ Test the human representation of a message """ message = Message.objects.get(pk=1) truncated_body = Truncator.words(message.body, 10) self.failUnlessEqual(message.__unicode__(), truncated_body)
def get_short_description(self, obj): t = Truncator(obj.post) return t.words(30, html=True)
def __unicode__(self): """ Human representation, displaying first ten words of the body. """ truncator = Truncator(self.body) truncated_body = truncator.words(10) return "%(truncated_body)s" % {'truncated_body': truncated_body}
def truncatehtml(string, length): truncator = Truncator(string) return truncator.words(length, html=True)