Rails Toc Generator работает, в браузера выпускает атрибут ID в тегах H1CSS

Разбираемся в CSS
Ответить
Anonymous
 Rails Toc Generator работает, в браузера выпускает атрибут ID в тегах H1

Сообщение Anonymous »

Несколько месяцев назад у меня была идея и пошла на нее неправильно, но в основном это сработало. После того, как мой приятель @max посмотрел и дал мне несколько указателей, я вернулся к нему с некоторой помощью Моники. это работает . Я написал сервис и звоню, прежде чем сохранить в модели Rails. Оно работает. Вот оригинальный вопрос:
Простая таблица содержимого в рельсах не работает так, как предполагается, что < /p>
Quick Represhere, потому что это ведет мне летучие мыши. Я хочу создать содержимое для моего блога, Rails 8 App. У меня установлен текст действия Rails и используя редактор TRIX. У редактора TRIX есть кнопка «заголовок», которая просто защелкнет тег H1 в контенте. Я написал сервис, который вызывает из модели блога перед сохранением и перед обновлением. Сервис просмотрет контент и возьмет контент тегов H1. Он будет использовать этот контент для: < /p>

[*] Создать неупорядоченный список якорных тегов, указывающих на атрибут идентификатора H1 с захваченным контентом. < /Li> < Br /> Он создаст атрибут ID для тега H1 и переписывает контент. Концепция проста. Вы делаете это в HTML все время. Если в разделе, div, элемент имеет атрибут ID, то вы можете нацелиться на это с помощью якоря. Я делаю это на своей домашней странице, чтобы нацелиться на определенные части информационной страницы. Полем Я вижу в журналах рельсов, где контент изменен и сохранен. Я могу отобразить контент на веб -странице, используя метод TO_S или метод TO_TRIX_HTML или метод TO_HTML и проверить атрибут ID в корпусе контента. Однако при рендеринге контента, как и обычно, браузер не включает атрибут ID для тега H1. Я поинтересовался с AI Google Browser, который должен был запустить JavaScript. Это вернулось с да, это могло видеть, что действительно должен быть атрибут ID, но браузер не отображал его. Это предположило, что какой -то подключен или какой -то другой JavaScript его удалял. Это происходит как в Chrome Browser, так и в Firefox. Просматривая мои плагины и код приложения, я не вижу, что может вызвать это. Вот TOC_GENERATOR в репо для обзора:
https://github.com/developer3027/milk-r ... nerator.rb> Я оставил код и генератор на месте, сохранить TOC в представлении. Приложение настроено с администратором для создания различных вещей, включая статьи в блоге. После установки вы можете запустить семена для создания учетной записи администратора. Затем при запуске нажмите «Кофейную кружку», чтобы войти в систему. Создайте любую статью, используя заголовок. При сохранении TOC и нового контента создаются. Вам нужно будет добавить @blog.toc обратно в представление для шоу (я сделал это в этом примере). Вот настройка, < /p>
Модель: < /p>
# before update or create run process_body
before_save :process_body
# Process the body content of a blog post by extracting the HTML content
# from the rich text body, generating a table of contents from any headings,
# and modifying the body content by adding ids to the headings so that they
# can be linked to from the table of contents.
# This process_body method is handled by the TocGenerator service.
def process_body
# Extract the HTML content from the rich text body
body_content = content.to_s

# Use the service to generate TOC and modify body content
result = TocGenerator.new(body_content).generate

self.toc = result[:toc] # Update the TOC
self.content = result[:body] # Update the :content with modified body
end
< /code>
контроллер: < /p>
# POST /milk_admin/blogs
#
# Creates a new blog post using provided blog parameters.
# Associates the blog post with the current milk admin.
#
# On success:
# - Sets the image URL if an image is attached.
# - Redirects to the blogs listing page with a success notice.
# - Renders the blog as JSON with a 201 status code.
#
# On failure:
# - Renders the new blog form with an unprocessable entity status.
# - Renders the errors as JSON with an unprocessable entity status.

def create
@blog = Blog.new(blog_params)
@blog.milk_admin_id = current_milk_admin.id

respond_to do |format|
if @blog.save
# @blog.process_body # Call process_body to ensure TOC and body are updated
set_image_url(@blog)
format.html { redirect_to milk_admin_blogs_path, notice: "Blog was successfully created." }
format.json { render json: @blog }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @blog.errors, status: :unprocessable_entity }
end
end
end

# PATCH/PUT /milk_admin/blogs/1
#
# Updates a blog using the given blog parameters.
# Associates the blog post with the current milk admin.
#
# On success:
# - Sets the image URL if an image is attached.
# - Redirects to the blogs listing page with a success notice.
# - Renders the blog as JSON with a 201 status code.
#
# On failure:
# - Renders the new blog form with an unprocessable entity status.
# - Renders the errors as JSON with an unprocessable entity status.
def update
@blog.milk_admin_id = current_milk_admin.id
respond_to do |format|
if @blog.update(blog_params)
# @blog.process_body # Call process_body to ensure TOC and body are updated
set_image_url(@blog) if @blog.blog_image.attached?
format.html { redirect_to milk_admin_blogs_path, notice: "Blog was successfully updated." }
format.json { render :show, status: :created, location: @blog }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @blog.errors, status: :unprocessable_entity }
end
end
end
< /code>
toc_generator - Service: < /p>
# Use the Nokogiri gem to generate the table of contents from the HTML content of the body (content)
# Using the default trix editor, using the Title button provides a h1 tag,
# search through the body content and generate the table of contents from the h1 tags content.
# Add the same id attribute to the h1 tags so that we can link to them from the table of contents.
class TocGenerator
# Initialize a new TocGenerator with the given body string.
#
# @param [String] body the body content to generate the table of contents from.
def initialize(body)
@body = body
end

# Returns a hash with keys :toc and :body.
#
# The :toc key maps to a string containing a table of contents generated from
# the headings in the body content.
#
# The :body key maps to the body content with the headings modified to have
# ids matching the text of the headings, for linking from the table of
# contents.
def generate
doc = Nokogiri::HTML::DocumentFragment.parse(@body)
headings = doc.css("h1")

return { toc: "", body: @body } if headings.empty?

toc = generate_toc(headings)
modified_body = modify_headings_with_ids(headings, doc)

{ toc: toc.html_safe, body: modified_body.html_safe }
end

private

# Generates an HTML table of contents from the given headings.
#
# @param [Nokogiri::XML::NodeSet] headings a collection of h1 elements from
# which to generate the table of contents.
# @return [String] an HTML string representing the table of contents, where
# each item links to the corresponding heading.

def generate_toc(headings)
toc = "
  • "
    headings.each do |heading|
    id = heading.text.gsub(/\s+/, "-").downcase
    toc += "#{heading.text}"
    end
    toc += "
"
toc
end

# Modifies the given headings by adding an id attribute to each one.
#
# The id is generated by downcasing the heading text and replacing any spaces
# with hyphens. If the heading already has an id, we don't overwrite it.
#
# @param [Nokogiri::XML::NodeSet] headings a collection of h1 elements from
# which to generate the ids.
# @param [Nokogiri::HTML::DocumentFragment] doc the document fragment in which
# the headings exist.
# @return [String] the modified HTML document fragment as a string.
def modify_headings_with_ids(headings, doc)
headings.each do |heading|
id = heading.text.gsub(/\s+/, "-").downcase
heading["id"] = id unless heading["id"] # Only set id if it doesn't exist
end
doc.to_html
end
end
< /code>
Показать блог Показать: < /p>







MILK-00 Blog Articles



Find me on

Welcome to the ramblings of my learning journey.









Author:
Created:

Category:










< /code>
Это самое близкое, что я получил для выполнения этой работы. Кажется, все это любит, кроме браузера, и я в растерянности. Приложение - Rail 8 Running Ruby 3.3.0 с Tailwind и PostgreSQL. Пожалуйста, просмотрите первоначальную проблему, хотя это действительно не имеет ничего общего с этой проблемой. Макс, если вы там, не подходите к этому правителю, мои суть готовы. Я действительно мог бы использовать вашу супер -силу помощь здесь.

Подробнее здесь: https://stackoverflow.com/questions/793 ... in-h1-tags
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «CSS»